Reputation: 1048
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.
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.
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
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
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.
You have same id set with two radio buttons, give unique id to radio button and use the above code.
Upvotes: 2
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
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