.focus()无法在Javascript函数中使用

时间:2013-02-26 01:58:15

标签: javascript html html5 forms

我有一个简单的表单,其中包含名字和姓氏的字段以及称呼。我有一个javascript函数,应该验证字段是否为空或超过25个字符。除了.focus()之外,该函数主要起作用;该页面只是重新加载。不知道我做错了什么,请指教。提前谢谢。

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>

1 个答案:

答案 0 :(得分:2)

变化:

onsubmit="validate();"> 

为:

onsubmit="return validate();">