Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
16
rated 0 times [  21] [ 5]  / answers: 1 / hits: 16240  / 13 Years ago, thu, january 5, 2012, 12:00:00

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;
}
}


And here is the form.....



<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!


More From » forms

 Answers
106

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;
}
}


DEMO


[#88209] Wednesday, January 4, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jarrettw

Total Points: 300
Total Questions: 98
Total Answers: 103

Location: Saudi Arabia
Member since Mon, Sep 5, 2022
2 Years ago
;