tags:

views:

231

answers:

3

following code work fine but 1 error

$(document).ready(
function() {


 $("#myCheckboxes input[type='checkbox']").change(function() {
    var checked = $("#myCheckboxes input[type='checkbox']:checked").length;

        if(checked == 4){
           $("#myCheckboxes input[type='checkbox']")
            .attr('disabled',true)
            .find(':checked')
            .attr('disabled',false)
    } else {
        $("#myCheckboxes input[type='checkbox']").attr('disabled',false);
    }


 });
 });

after selection become 4 all check box become disable even selected one, but i don't want to disable selected check box's.

Thanks

+10  A: 

Try this

$("#myCheckboxes :checkbox:not(:checked)").attr('disabled', true)

instead of

$("#myCheckboxes input[type='checkbox']")
    .attr('disabled',true)
    .find(':checked')
    .attr('disabled',false)
powtac
Yeah, I believe that's exactly what the original questioner wanted.
Bob Aman
Just to add (I voted up) could also use the :checkbox selector, as in '#myCheckboxes :checkbox:not(:checked)'...
karim79
yes this exactly what i was looking for, gr8 solution and thanks you vary much for that...
air
A: 

I already adjusted my answer to your original question (which you oddly posted as another question on SO). I had a small typo in it which has since been fixed following your comment: http://stackoverflow.com/questions/1560079/set-total-number-of-checkbox-in-array

KyleFarris
dear sir, you again do it wrongly, actually i want to disable unchecked one, my purpose is that user can't select more than 4 options... anyway thanks for your help
air
+1  A: 

You should note that this isn't the way to enable/disable DOM elements.
Consider:

<input type="checkbox" disabled='true' />
<input type="checkbox" disabled='false' />

Contrary to how it seems, because they have the disabled attribute, both controls are disabled!
This is for back-compatibly, when HTML had <input type="checkbox" disabled /> - the value is ignored.

The common why to disable an element is by

<input type="checkbox" disabled='disabled' />

Therfore, the proper way of doing this with jQuery is:

$("input:checkbox").attr('disabled', 'disabled'); //disable
$("input:checkbox").removeAttr('disabled'); //enable
Kobi