2013-02-26 123 views
2

我有簡單的形式,包含名字和姓氏字段以及稱呼。我有一個JavaScript函數應該驗證,如果字段或空或超過25個字符。該函數大多數工作,除了.focus();該頁面只是重新加載。不知道我做錯了什麼,請告知。提前致謝。.focus()在Javascript中不能使用功能

function validate(){ 
//alert ("TEST!!!"); 
var first = document.getElementById('firstname').value; 

if (first.length == 0 || first.length > 25){ 

     alert ("Please enter your first name, no longer than 25 chracters."); 

     document.getElementById('firstname').focus(); 

     return false; 

     } 

var last = document.getElementById('lastname').value; 
if (last.length == 0 || last.length > 25){ 

    alert ("Please enter your last name, no longer than 25 characters."); 

    document.getElementsByName('lastname').focus(); 

    return false; 

    } 

var title = document.getElementById('title').value; 
if (document.getElementById('title').selectedIndex == 0){ 

    alert ("Please select your salutation"); 

    document.getElementById('title').focus(); 

    return false; 
} 

return true; 

}

在HTML的形式是:

<form name="name" form id="name" method="post" onsubmit="validate();"> 
     Salutation: <select name="title" select id="title"> 
      <option selected="Please Select">Please select</option> 
      <option value="Mr.">Mr.</option> 
      <option value="Mrs.">Mrs.</option> 
      <option value="Miss">Miss</option> 
     </select><br><br> 
     First Name : <input type="text" input id="firstname" name="firstname"> 
     Last Name : <input type="text" input id="lastname" name="lastname"><br><br> 
     <input type="submit" value="Submit"><br><br> 
</form> 

回答

2

變化:

onsubmit="validate();"> 

到:

onsubmit="return validate();"> 
+0

比k你!這解決了它!這樣一個簡單的錯誤! .__。 – 2013-02-26 02:05:25