我有两个功能:一个是验证表单名称字段中的信息,另一个是获取这些字段中的信息并将它们打印在警报框中。这些功能分别工作正常。我必须同时调用它们,所以我创建了一个包装函数。该函数运行,但它刷新而不是聚焦。奇怪的是,如果我检查第一个字段,一切都很好,包括 .focus();,但是当我尝试验证第二个字段时,.focus(); 不起作用,页面刷新。任何帮助,将不胜感激。(我试图修改我的第一个问题以添加它,但是当我去保存它时,什么也没发生。)
function main() {
var test = validate();
if (test == true) {
concatinate();
return true;
}
}
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;
}
function concatinate() {
var first = document.getElementById('firstname').value;
var last = document.getElementById('lastname').value;
var title = document.getElementById('title').value;
var fullname = title + " " + first + " " + last;
var printFull = "Welcome, " + fullname;
alert(printFull);
}
<form name="name" form id="name" method="post" onsubmit="return main();">
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>