我想知道,是否有一个 JavaScript 命令(我正在寻找的东西的正确名称是什么?),我可以在其中选择表单中的所有输入框,而不仅仅是一个?
例如:
function checkform(id){
var theForm = document.getElementById( id );
if (theForm.surname.value == '') {
alert( "you didn't type in your surname");
theForm.surname.focus();
return false;
}
else if (theForm.surname.value.length == 0) {
alert( 'You\'ve left some of the fields blank' );
theForm.surname.focus();
return false;
}
return true;
}
我有这个代码。其目的是检查表单中的每个输入框以查看是否已输入信息,如果未输入,则在用户提交表单时出现警报。
有没有一种方法可以更改这段 JavaScript,以便检查每个输入框,而不仅仅是姓氏输入框(如示例所示)。
最佳答案
方法getElementsByTagName
可以为您提供所有输入,elements
属性将保存表单中所有控件的NodeList。
var nodeList = theForm.getElementsByTagName('input');
或
var nodeList = theForm.elements;
关于JavaScript 表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15055765/