Page 1 of 1

click up to 5 checkboxes

Posted: Wed Mar 04, 2009 10:18 am
by buzzby247
hi there ppl.

i have a competition running whereby i want the user to click up to 5 answers. the user has a choice of 12 answers (12 checkboxes). i am stuck as to how to code the script so the maximum number of checkboxes that can be ticked is 5. any helpers please?

Re: click up to 5 checkboxes

Posted: Wed Mar 04, 2009 2:02 pm
by kaszu
Count how many checkboxes user has checked. When count reaches the limit, disable unchecked checkboxes.
If you are using jQuery (haven't tested following code):

Code: Select all

var inp = $('input[type="checkbox"]');
inp.click(oncheck).change(oncheck);
 
function oncheck () {
    var cnt = inp.filter(':checked').count;
    if(cnt >= 5) {
        inp.not(':checked').attr('disabled', true);
    } else {
        inp.attr('disabled', false);
    }
}

Re: click up to 5 checkboxes

Posted: Wed Mar 04, 2009 3:51 pm
by VladSun
Using a simple JS is still simple:

Code: Select all

<div id='checkBoxContainer'>    <input type="checkbox" name="">    <input type="checkbox" name="">    <input type="checkbox" name="">    <input type="checkbox" name="">    <input type="checkbox" name="">    <input type="checkbox" name="">    <input type="checkbox" name="">    <input type="checkbox" name="">    <input type="checkbox" name="">    <input type="checkbox" name=""></div> <script language="JavaScript">    var checked = 0;    var checkboxes = document.getElementById('checkBoxContainer').getElementsByTagName('input');        for (var i=0; i<checkboxes.length; i++)        if (checkboxes[i].type == 'checkbox')            checkboxes[i].onchange = function ()            {                if ( (checked += this.checked ? 1 : -1) > 5)                {                    checked--;                    this.checked = false;                }            }</script>
PS: It appears that 13 code lines of pure JS works as good as 11 code lines of jQuery + the jQuery itself :twisted:

Re: click up to 5 checkboxes

Posted: Thu Mar 05, 2009 10:31 am
by pickle
@~ kaszu - You need to remove the "disabled" attribute, not just set it to false. Please also use the tags to colour your code.

Re: click up to 5 checkboxes

Posted: Thu Mar 05, 2009 1:38 pm
by kaszu
Forgot about highlighting :oops:
Setting 'disabled' to true/false does the trick (checked on FF, IE6, IE7, Safari), but I remember that I was removing this attribute in JS in previous project (wasn't using jQuery). Only can't remember why at the moment, anyone!?

onchange is fired only after focus is lost in IE, so you need to bind to onclick also.

I agree that jQuery was way too much for this problem, but I was tired and couldn't/didn't wanted to think (bad excuse, I know :D).