Dan Dan - 4 months ago 7
Javascript Question

Javascript validation for multiple textboxes

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!

Answer

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

Comments