Skip to content Skip to sidebar Skip to footer

Checkbox Validations

I cant simply get my head around javascript validations. I've seen tutorials and its just not getting to me. Someone please give me a SIMPLE step by step guide on how I can add val

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.

enter image description here

Post a Comment for "Checkbox Validations"