Reputation: 10473
Hi I'm trying to validate the option that the user check and if they didn't checked anything in the page then will display an error message and let them check before it will continue
here is my code
for (var j=0;j<f10; j++ )
{
if (document.pizza.field10[j].checked == true)
{ check2 ++ ; }
}// for ends heree
if (check2 == 0 )
{
alert("Error!!: Please select atleast one topping for Pizza.");
document.pizza.field10.focus();
return false;
}
/*Field05 Validation Ends Here*/
and var f10 = document.pizza.field10.length ;// field05
this is the total length and f10
is the variable.
I don't know what is wrong even the user didn't check the option it still continue
Thanks
EDIT here is the html code
<p>Toppings:</p>
<table width="400" class="toppings">
<tr>
<td><label>
<input type="checkbox" name="field10" value="chicken" />
Chicken</label></td>
<td><label>
<input type="checkbox" name="field10" value="beef" />
Beef</label></td>
</tr>
<tr>
<td><label>
<input type="checkbox" name="field10" value="green pepper" />
Green Pepper</label></td>
<td><label>
<input type="checkbox" name="field10" value="olives" />
Olives</label></td>
</tr>
<tr>
<td><label>
<input type="checkbox" name="field10" value="onions" />
Onions</label></td>
<td><label>
<input type="checkbox" name="field10" value="red pepper" />
Red Pepper</label></td>
</tr>
</table>
EDIT2: here is the form tag
<form name='pizza' id='pizza' method='post'
action='https://cs.senecac.on.ca/~int222/cgi-bin/assign3.cgi'
onsubmit='return FormValidation();'>
and here is the submit button
<p> <input class="button" name="Submit" type="submit" value="Submit" /> <input class="button" name="reset" type="reset" value="Reset" />
</p></div>
Upvotes: 0
Views: 315
Reputation: 26167
Aside from being positive check2
is set to 0
before your code executes and possibly re-naming your submit button (per my comment). I would try using the debugging tool firebug to step through your FormValidation()
function to make sure your code is actually retrieving the DOM nodes and see where check2
is getting incremented.
Upvotes: 1
Reputation: 446
The problem was
document.pizza.field10.focus();
I think, you cannot focus buttons or checkbox fields :) Thanks all for help.
Upvotes: 1
Reputation: 3162
You need to change your code to something like this JSFiddle
The important part being this:
var fields = document.getElementsByName("field10");
( And the complete code here for when the JS Fiddle Expires )
var check2 = 0;
var fields = document.getElementsByName("field10");
for (var j = 0; j < fields.length - 1; j++) {
if (fields[j].checked == true) {
check2++;
}
} // for ends heree
if (check2 == 0) {
alert("Error!!: Please select at least one topping for Pizza.");
return false;
}
Upvotes: 1