I am trying to check multiple checkboxes using one with jQuery. I know how to do this to check all checkboxes or to check multiple if they have ids. I want to be able to do this without that though.
All of my checkboxes are in a similar grouping. I have them grouped in a consistant way.
I have my work on a fiddle here.
Here is my code
window.onCheck = function () {
var totals = [0, 0, 0];
$('tr.checkRow').each(function () {
var $row = $(this);
if ($row.children('td:first').find('input:checkbox').prop('checked')) {
$(this).find('td.imageBox').each(function (index) {
var $imageBox = $(this);
if ($imageBox.children('img:first').attr('src').indexOf('yes') >= 0) {
++(totals[index]);
}
});
}
});
$('#total1').text(totals[0]);
$('#total2').text(totals[1]);
$('#total3').text(totals[2]);
};
window.onCheckForm = function (cb) {
var $cb = $(cb);
var $table = $cb.parents("table");
$('input.subFieldCheck').find($table).prop('checked', function () { return cb.prop('checked')});
}
My problem is with the onCheckForm function.
Thank you.
Note: I started writing this answer for a duplicate of this question and realized I couldn't post this, so I posted it here instead. The table structure is different and a lot simplified in this answer.
Lets start off with a very simple table with a checkbox column:
Here, I have a checkbox in the header along with a label for accessibility purposes (you may hide the label if you wish).
I've also given the header cell an ID and used the
headers
attribute for thetd
elements. This isn't absolutely necessary for what we're doing, however it seems like an appropriate case to use theheaders
attribute. If you ever want to move the checkbox to another column for certain rows, you can just add theheaders
attribute to that cell.Here is some JavaScript code:
We are binding a function to the
change
event to the checkbox in the header.The selector will look for all checkboxes that are children of
td
elements that contain the IDtoggler
in a space-separated list of tokens in theheaders
attribute.The
.prop()
method sets thechecked
property of the checkboxes to match the value of thechecked
property of the one in the header ("this").Our basic functionality is done here.
We can make improvements though, by changing the state of the checkbox at the top to match the state of the checkboxes in the rows.
The state of the header checkbox should be:
n
) are checkedn
are checkedWhere
n
indicates all the checkboxes.To do this, we bind a function to the
change
event of each of the boxes in the table rows:I'm using
.each()
here to loop through all of the appropriate checkboxes to determine whether all, none, or some are checked.See the jsFiddle demo.
Hope this helps, I sure learned quite a bit while answering the question!
See this fiddle for a cleaner way:
http://jsfiddle.net/W75dy/19/