Checkbox Validations
Solution 1:
It looks like you actually want radio buttons, not checkboxes.
If that is the case, use this:
<formaction=""method="post"><label><inputtype="radio"name="vote"value="Conserv" /> Conservative</label><br /><label><inputtype="radio"name="vote"value="LibDem" /> Liberal Democrats</label><br /><label><inputtype="radio"name="vote"value="Labour" /> Labour</label><br /></form>
Then, in whatever server-side code you have, the vote
POST variable will have either "Conserv"
, "LibDem"
or "Labour"
depending on user choice.
Solution 2:
So you want to validate that, based on your comment, at least two of these checkboxes are checked? I would give them all the same name:
<input name="partyAffiliation"type="checkbox" value="Conservatives" /> Conservative
<input name="partyAffiliation"type="checkbox" value="Liberal Democrats" /> Liberal Democrats
<input name="partyAffiliation"type="checkbox" value="Labour" /> Labour
Then loop them and see how many are checked. document.getElementsByName
will give you the checkboxes, each of which will have a checked
property.
var allCbs = document.getElementsByName("partyAffiliation");
var numChecked = 0;
for(var i = 0, max = allCbs.length; i < max; i++)
if (allCbs[i].checked)
numChecked++;
if (numChecked < 2)
alert("Select at least two parties!");
I don't know the details of your project, but I'll just mention that jQuery will make the above code quite simple, if using this library is something you're not opposed to:
var numChecked = $("input[name='partyAffiliation']:checked").length;
if (numChecked < 2)
alert("Select at least two parties!");
EDIT
In response to a comment below, don't worry about having multiple inputs with the same name. Your server-side code should receive a comma delimited list of all (selected) values associated with that name. So if you check all three checkboxes, you'd see something like the below.
Post a Comment for "Checkbox Validations"