<TD>
<input type="text" name="name1" size="35" class="mustEnter" />
</TD>
<TD>
<input type="radio" name="name2" value="val1" class="mustCheck"/>
<input type="radio" name="name2" value="val2" class="mustCheck"/>
<input type="radio" name="name2" value="val3" class="mustCheck"/>
</TD>
<TD>
<input type="checkbox" name="name3" value="valA" class="mustCheck"/>
<input type="checkbox" name="name3" value="valB" class="mustCheck"/>
<input type="checkbox" name="name3" value="valC" class="mustCheck"/>
</TD>
I want to test if the a mandatory field (in this case radio and check boxes) were checked, but it does not work.
each() passes through the radio buttons (or check boxes) three times and $(this).length is always 1. I want to avoid testing by name as the list could be long. What would be the solution?
valid = true;
$("#studentForm input.mustEnter, #studentForm input.mustCheck").each(function() {
if( ($(this).hasClass('mustEnter') && $(this).val() != false )
|| ($(this).hasClass('mustCheck') && $(this).length > 0) ) {
$(this).parent().removeClass("errorHighlight");
}
else {
$(this).parent().addClass('errorHighlight');
valid = false;
}
I found the way:
As I have two classes,
mustEnterfor regular fields andmustCheckfor radio and check-boxes, I use the mustCheck class to get the name of the element and then use the name to test if at least one in the group (of three in this case) was checked. I only need to use themustCheckclass in only one item of the group.