Edin Puzic
Edin Puzic

Reputation: 1048

Toggle (enable / disable) all checkboxes in an HTML table with jQuery

I want to add an Enable all checkbox in an HTML <table>, that toggles all checkboxes inside that <table>.

I can't get it to work.

My Jquery :

var elementName = 'TestName';

$('input[familyname="TestName"]').on('click', function() {
    if ($("input[familyname='" + elementName + "']").is(':checked')) {
        $(this).find('tr').nextAll('tr').find('input').prop('checked', true);
    } else {
        $(this).find('tr').nextAll('tr').find('input').prop('checked', false);
    }
});

See also this Fiddle.


Update:

I got it to work with this code:

var elementName = 'TestName';
var $checkboxes = $('.table-list').find('input'); 

$('input[familyname="TestName"]').on('click', function() {
    $checkboxes.prop('checked', $(this).is(':checked'));
});

However, there is bug when I want to add more tables. See this Fiddle.

Upvotes: 0

Views: 943

Answers (4)

John Slegers
John Slegers

Reputation: 47081

This is a simple but optimal way to achieve the desired effect, that works for any number of checkbox groups :

var elementName = 'TestName';

$('input[familyname="' + elementName + '"]').on('click', function(e) {
    $(this)
        .closest('.table-list')
        .find('input')
        .prop('checked', this.checked);
});

(see also this Fiddle)

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

You have to change your code like below,

var elementName = 'TestName';
$('input[familyname="' + elementName + '"]').on('click', function() {
  var elems = $(this).closest('table.table').find('tr input');
  elems.prop('checked', this.checked)
});

tr is parent in our context, so .find() over $(this) will not work out. So we have to use .closest() to grab the parent table and from that we can fetch all the required input - check box elements.

DEMO


You have same id set with two radio buttons, give unique id to radio button and use the above code.

DEMO

Upvotes: 2

yfet
yfet

Reputation: 69

Try this :

$(document).on('click', '#switchall1', function() {

if ($(this).is(':checked')) {
    $(this).closest('table').find('tbody tr input').prop('checked', true);

}
else {
    $(this).closest('table').find('tbody tr input').prop('checked', false);
}

});

Upvotes: 0

void
void

Reputation: 36703

If you are putting in thead then you can't just directly do .find() instead traverse to tbody and select all input with type=checkbox, like:

 $(this).closest("table").find('tbody input[type=checkbox]').prop('checked', true);

Similarly do:

 $(this).closest("table").find('tbody input[type=checkbox]').prop('checked', false);

Upvotes: 1

Related Questions