By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,403 Members | 880 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,403 IT Pros & Developers. It's quick & easy.

Checkbox form validation - how to make a user select 4 check boxes

P: 14
Hello,
Checkbox form validation - how to make a user select 4 check boxes?
I have a question of a few checkboxes and how do I require a user to check 2 checkboxes (no more, no less)?

Here is my form:
<input type="checkbox" name="color" id="q" value="a" />A<BR />
<input type="checkbox" name="color" id="q2" value="b" />b<BR />
<input type="checkbox" name="color" id="q3" value="c" />c<BR />
<input type="checkbox" name="color" id="q4" value="d" />d<BR />

Thanks much.
May 11 '07 #1
Share this Question
Share on Google+
12 Replies


gits
Expert Mod 5K+
P: 5,320
hi,

at the time you want to check you have different possibilities to achieve your goal :) you may loop through the elements and ask for check-attribs of them. if you find 2 checked ones you are done ... you may break the loop now and all is ok ...

you may also respond to the click-event at runtime ... when clicked/checked you might store the id of the checked element in an js-object or whatever you want to use for that ... then ... the right time you ask that object for stored data ... and if you find two or more stored ids ... you are done ...
May 11 '07 #2

pbmods
Expert 5K+
P: 5,821
Here's what I'm thinking...

[HTML]
<!-- Set to 'text' instead of 'hidden' so you can watch it make magic! -->
<input id="color0" name="color[]" type="text" value="" />
<input id="color1" name="color[]" type="text" value="" />

<p>
<input id="check0" type="checkbox" onclick="pushChex(this);" value="a" />a<br />
<input id="check1" type="checkbox" onclick="pushChex(this);" value="b" />b<br />
<input id="check2" type="checkbox" onclick="pushChex(this);" value="c" />c<br />
<input id="check3" type="checkbox" onclick="pushChex(this);" value="d" />d<br />
</p>

<script type="text/javascript">
var $chex = [null, null];
function pushChex($element) {

// If we check a box, add it to the array and shift off the first one.
if($element.checked) {
$chex.push($element);

$uncheck = $chex.shift();
if($uncheck)
$uncheck.checked = false;

// If we uncheck a box, remove it from the array and push/unshift a null onto the other side.
} else {
if($chex[0] == $element)
$chex[0] = null;
else {
$chex.pop();
$chex.unshift(null);
}
}

// Update hidden inputs.
var $input;
for(var $i = 0; ($i < $chex.length) && ($input = document.getElementById('color' + $i)); $i++)
$input.value = ($chex[$i]
? $chex[$i].value
: ''
);
}
</script>
[/HTML]

Methinks I had way too much fun with this one.

[EDIT: You're still going to have to check for > 0 checked when the User submits the form, and as much fun as this code looks, I'm pretty sure there's a more efficient way to do it ;)]
May 12 '07 #3

gits
Expert Mod 5K+
P: 5,320
yep ... thats a fun thing ... and I tried it too ... using your example and changed it ... please excuse me ;)

[HTML]<p>
<input id="check0" type="checkbox" onclick="pushChex(this);" value="a" />a<br />
<input id="check1" type="checkbox" onclick="pushChex(this);" value="b" />b<br />
<input id="check2" type="checkbox" onclick="pushChex(this);" value="c" />c<br />
<input id="check3" type="checkbox" onclick="pushChex(this);" value="d" />d<br />
</p>

<p>
<div id="chex_content"></div>
</p>

<script type="text/javascript">
var $chex = {
length: 0,
eles : {}
};

function pushChex($element) {
if (typeof $chex.eles[$element.id] == 'undefined') {
if ($chex.length < 2) {
$chex.eles[$element.id] = $element;
$chex.length++;
} else {
$element.checked = false;
alert('only 2 checked boxes allowed');
}
} else {
delete $chex.eles[$element.id];
$chex.length--;
}

// we write to the div to show what we have checked for now
// thats not needed for functionality only for demo

var $ct = document.getElementById('chex_content');
$ct.innerHTML = '';

for (var i in $chex.eles) {
$ct.innerHTML += $chex.eles[i].id + '<br>';
}
}
</script>[/HTML]

so we only have to ask $chex for length to have the condition fullfilled that 2 have to be checked ...
May 12 '07 #4

P: 14
Thanks.
If a user check less than 2, it does not pop up errors.
I like to have a user to check at least 2 and NO more than 2.
Thanks.
May 14 '07 #5

gits
Expert Mod 5K+
P: 5,320
at the time you want to check that ... probably on submitting the form, you have to ask $chex for length == 2 (assuming you use the code with the $chex-object) ... if this returns false, then you produce the error AND avoid submitting the form ... something like that:

Expand|Select|Wrap|Line Numbers
  1. // call that function on submit or at the point you want to check for
  2. // 2 checked boxes
  3.  
  4. function check_your_checkboxes() {
  5.     var val = $chex.length == 2;
  6.  
  7.     if (!val) {
  8.         alert('two checked boxes required');
  9.     }
  10.  
  11.     return val;
  12. }
  13.  
  14. // use the function to check within one that should submit the form ...
  15. // when returning false you don't perform the submit otherwise you do
  16.  
May 14 '07 #6

pbmods
Expert 5K+
P: 5,821
yep ... thats a fun thing ... and I tried it too ... using your example and changed it ... please excuse me ;)
You mean... you took some existing code and changed it to suit your purposes?

My goodness. What is this world coming to?

If a user check less than 2, it does not pop up errors.
I like to have a user to check at least 2 and NO more than 2.
That one you're gonna have to do manually.

Note in gits's post:

so we only have to ask $chex for length to have the condition fullfilled that 2 have to be checked ...
May 14 '07 #7

P: 14
Can I require a user to check at least 2 but No more than 2 boxes by using onBlur directly on the form. Fore example. when a user check ONLY 1 box and move to next field, then 1 error message pops up. I already have 1 function to check for empty checkboxes and don't know how to modify it to check at least two boxes.

var checkboxCk = false;
for (i = 0; i < document.frmname.chkFields.length; i++) {
if (document.frmname.chkFields[i].checked)
checkboxCk = true; }
if (!checkboxCk) {
msgbox = msgbox + "\n Question #2, please check on this question";
}

Thanks.
May 14 '07 #8

gits
Expert Mod 5K+
P: 5,320
You mean... you took some existing code and changed it to suit your purposes?

My goodness. What is this world coming to?
;) yep ... this world is bad and sad and ugly, nobody makes things hisself ... we reuse, refactor, steal ... shame on me :)

and now back to the problem: i assume the following now ... you've got your 4 checkboxes, probably as part of a survey, and before the user may switch to the next part of the survey you want to check, that he has exactly 2 checkboxes checked?

first: the function above checks already that you don't check more then 2 ... otherwise you get an alert ...

second: you are right to determine the point of getting the event that fires when the user wants to switch from your checkbox-section to an other ... but using onblur is sometimes annoying to the user ... until you give him the error without knowing whether he had checked the 2 boxes or not ... and he may think that this error is stupid, because he wanted to check 2 boxes ... perhaps you gave him a hint above the section, that he has to ... do you understand what i mean? ... its better to check after he's done, not during his actions ... so my advice would be: give every section a done-action (button or next-question-link or whatever) ... the user performs a click and you may check for whatever you want at this point ... and perhaps prepare your next question with the given results ... doing things implicit sometimes annoys the user until you need to know what he expects from your app ... a button/link/orwhatever to click is common ... and he knows what to do ...

if you don't want such an additional control i would recommend to rather check onfocus in the next section, than in your checkboxes ... assuming you use the above checkfunction that always responds to the click-event ...

hope i gave you an idea for achieving your goal?
May 14 '07 #9

P: 14
I agree with you not to use onBlur.
When I added this function on my existing JS function, it does not work.
function check_your_checkboxes() {
var val = $chex.length == 2;
if (!val) {
alert('two checked boxes required');
}
return val;
}

Because I already have this to check for empty field check box.
var checkboxCk = false;
for (i = 0; i < document.frmname.chkFields.length; i++) {
if (document.frmname.chkFields[i].checked)
checkboxCk = true; }
if (!checkboxCk) {
msgbox = msgbox + "\n Question #2, please check on this question";
}

Can you show me how to combine them together?

Thanks.
May 14 '07 #10

gits
Expert Mod 5K+
P: 5,320
Because I already have this to check for empty field check box.

Expand|Select|Wrap|Line Numbers
  1. var checkboxCk = false;
  2.  
  3. for (i = 0; i < document.frmname.chkFields.length; i++)  {
  4.     if (document.frmname.chkFields[i].checked) checkboxCk = true; 
  5. }
  6. if (!checkboxCk) {
  7.     msgbox = msgbox + "\n Question #2, please check on this question";
  8. }
  9.  
Can you show me how to combine them together?

Thanks.
wait a moment ... i try to recognize what you have done:

you are checking for the 'correctness' of checked checkboxes with the function you posted above? this checks every checkbox and produces an error if one is found without to be checked ... and now you want to break through that logic when 2 boxes are checked? ... and you don't want to use one of our check-functions above until you prefer to use your own check?

if i'm right ... you cannot use the check that asks for the length of $chex until you wouldn't have $chex to ask for. otherwise you don't have to do anything else then replacing your code with the 'length'-check ... and voila: you would be done! everything you need is posted already. use the code i posted before, that remembers the checkbox-clicks within the $chex-object and replace your check with the code that asks for the length of $chex ... that together should do the job.

tell me exactly the point when you perform your check ... assuming you check your way you have to store a counter or something like that ... when the user checks a box you increase it and if you perform your check you additionally have to ask for your counter ... in a way that looks like:

Expand|Select|Wrap|Line Numbers
  1. if (!checkboxCk && counter != 2) {
  2.     // do whatever you want
  3. }
  4.  
note: you also have to decrease the counter when the user unchecks a box ... the drawback of that would be, that you always have to loop through your checkboxes ... it is not a performance-killer in the case of your 4 checkboxes, but generally it is a programming-rule to avoid loops whereever you can ...

so ... you need not to combine your and our solution ... they would be distinct ... if you prefer your check you have to extend your code ... otherwise simply replace it with ours ...

greetings ... don't hesitate to ask more questions ... i'm willing to help you but at this point you should explain more clearly what you want to do and when things should be done ...
May 15 '07 #11

P: 14
It worked perfectly.
Thanks.
May 15 '07 #12

gits
Expert Mod 5K+
P: 5,320
It worked perfectly.
Thanks.
cool ... ;)
May 15 '07 #13

Post your reply

Sign in to post your reply or Sign up for a free account.