Javascript表单验证

时间:2013-02-24 19:38:23

标签: javascript

我想知道,是否有一个JavaScript命令(我正在寻找的东西的名称是什么?)我可以在一个表单中选择所有输入框而不是一个?

E.g:

 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来检查每个输入框而不仅仅是姓氏(如示例所示)。

2 个答案:

答案 0 :(得分:0)

方法getElementsByTagName可以为您提供所有输入,elements属性将保存表单中所有控件的NodeList。

var nodeList = theForm.getElementsByTagName('input');

var nodeList = theForm.elements;

答案 1 :(得分:0)

我认为你需要document.getElementsByTagName()方法。您可以将其与当前函数链接起来,如下所示:

var inputs = document.getElementsByTagName('input'), // get all input tags in the document
    i = 0, // set counter to zero
    l = inputs.length; // get number of inputs you have found
for (i; i < l; i += 1) { // loop through the inputs you have found
    checkform(inputs[i].id); // send the id of each input to the `checkform` method
}

当然你可能想要重写你所拥有的功能以提高它的效率,但是你可以直接将它放到代码中(在checkform函数之外)并且它应该做你想要的。

相关问题