rahularyansharma
rahularyansharma

Reputation: 10755

disable only checkboxes which are in same div instead of all

I want to disable all checkboxes which are in same div when first checkbox is checked and enable again if its unchecked.

and its working for me check here

$('.cdls_content_wrapper input:checkbox:first').click(function () {
    alert('HI');
    $('.cdls_content_wrapper').find(':checkbox').slice(1).each(function () {
        if ($('.cdls_content_wrapper input:checkbox:first').is(':checked')) {
            $(this).attr("disabled", true);
        } else {
            $(this).attr("disabled", false);
        }
    });
});

but the problem is when i have another same div and click on that div first checkbox it do the same for all.

I want to make my function more general instead of specific to only one div.

Upvotes: 0

Views: 515

Answers (5)

frenchie
frenchie

Reputation: 51937

Just move the function out of the handler, like this:

function DoWork(TheDiv) {

   var IsFirstChecked;

   TheDiv.find(':checkbox').each(function () {

        if (typeof(IsFirstChecked) !== 'boolean') {
              IsFirstChecked = $(this).prop('checked');
         } else {
              $(this).prop('disabled', IsFirstChecked);
         }
    });
}

And then call it from anywhere:

$('.cdls_content_wrapper').find('input').click(function () {
    DoWork($(this).closest('table'));
});

$('.SomeOtherClass').find('input').click(function () {
    DoWork($(this).closest('table'));
});

Here's the working jsFiddle

Also, as per jQuery documentation, using .prop() is a better way to go than using .attr()

Upvotes: 0

Geo A. Fragedakis
Geo A. Fragedakis

Reputation: 134

Sorry mate i nailed it this time!

Just paste this :

$('.cdls_content_wrapper input:checkbox:first').click(function () {
    alert('HI');
    $(this).parent().parent().parent().find(':checkbox').slice(1).each(function () {
        if ($('.cdls_content_wrapper input:checkbox:first').is(':checked')) {
            $(this).attr("disabled", true);
        } else {
            $(this).attr("disabled", false);
        }
    });
});

Upvotes: 0

nix
nix

Reputation: 3302

You may add a class to allcheckbox and do it this way:

$('.cdls_content_wrapper input:checkbox.all').click(function(){
    if($(this).is(':checked')){
        $('input:checkbox',$(this).closest('tr').siblings()).attr("disabled", true);
    }else{
        $('input:checkbox',$(this).closest('tr').siblings()).attr("disabled", false);
    }
});

Sample fiddle..

Upvotes: 2

Arun P Johny
Arun P Johny

Reputation: 388316

Try

$('.cdls_content_wrapper').find(':checkbox:first').click(function () {
    $(this).closest('.cdls_content_wrapper').find(':checkbox').not(this).attr('disabled', this.checked)
});

Demo: Fiddle

Upvotes: 3

Manish Jangir
Manish Jangir

Reputation: 505

You have to use different class for your checkboxes in both divs

Upvotes: -1

Related Questions