2

我有一个简单的表格,其中包含名字和姓氏以及称呼的字段。我有一个 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>
4

1 回答 1

2

改变:

onsubmit="validate();"> 

到:

onsubmit="return validate();"> 
于 2013-02-26T01:59:20.257 回答