问题描述
我在弄清楚如何使用js验证文本框时遇到了一些麻烦.我有10个文本框,用户可以填写任何数字1-10,但不能填写0.这是我编写的js,但是只有在所有10个文本框都填满的情况下,它才返回true,而不仅仅是检查是否填充.
I am having some trouble figuring out how to validate my textboxes using js. I have 10 textboxes, the user can fill out any number 1-10, but cant fill out 0. Here is the js that I have written, but it only returns true if all 10 textboxes are filled, rather than just checking if one is filled.
function submitIt() {
if (document.isForm.Student_ID.value == null) {
alert ("You must enter a Colleague ID.");
return false;
} else {
return true;
}
}
这是表格.....
<form name="isForm" onSubmit="return submitIt()">
<input name="Student_ID" type="text" id="idField1" />
<input name="Student_ID" type="text" id="idField2" />
<input name="Student_ID" type="text" id="idField3" />
<input name="Student_ID" type="text" id="idField4" />
<input name="Student_ID" type="text" id="idField5" />
<input name="Student_ID" type="text" id="idField6" />
<input name="Student_ID" type="text" id="idField7" />
<input name="Student_ID" type="text" id="idField8" />
<input name="Student_ID" type="text" id="idField9" />
<input name="Student_ID" type="text" id="idField10" />
<input name="SUBMIT" type="submit" />
</form>
我意识到我可以更改所有名称,并检查每个名称,但是我试图避免代码中出现太多混乱,并且很好奇这样做的最佳方法.感谢您的任何帮助,谢谢!
I realize that I could change all of the names, and check each one, but I am trying to avoid that much clutter in my code, and am curious the best way to do this. Any help is appreciated, thanks!
推荐答案
您可以使用document.getElementsByName
获取所有这些文本框的集合.然后遍历它们,并确保至少填写了一个:
You can get a collection of all these textboxes with document.getElementsByName
. Then loop through them, and make sure at least one is filled in:
var allTbs = document.getElementsByName("Student_ID");
var valid = false;
for (var i = 0, max = allTbs.length; i < max; i++) {
if (allTbs[i].value) {
valid = true;
break;
}
}
这篇关于多个文本框的JavaScript验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!