1

我想知道,是否有一个 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 以检查每个输入框,而不仅仅是姓氏(如示例中所示)。

4

2 回答 2

0

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

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

或者

var nodeList = theForm.elements;
于 2013-02-24T19:42:48.863 回答
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函数之外),它应该做您想做的事情。

于 2013-02-24T19:43:08.133 回答