Learn and share. The simplest harmony.

 

[Code Snippet] jQuery : Checkbox & Table

Posted on February 23, 2010 and got 6 shouts so far

Today’s code snippet is how to automagically check/uncheck checkbox element by clicking a single row of a table using jQuery. Firstly we add click event on the table’s row, it will help us read click event on each row. Grab checkbox element on its row, check whether this checkbox was checked or not yet, then add checked or unchecked value on it.

 
$('table tr').click(function() {

	checkBox = $(this).children('td').children('input[type=checkbox]');

	if(checkBox.attr('checked'))
		checkBox.attr('checked', '');
	else
		checkBox.attr('checked', 'checked');
});


Now our row have functionality to check/uncheck checkbox element, but how about we add a little function to check/uncheck all checkbox in our table by clicking only one checkbox, here is the code :

$('.check-all').click(function() {

	checkBox = $('table tr').children('td').children('input[type=checkbox]');

	if($(this).attr('checked'))
		checkBox.attr('checked', 'checked');
	else
		checkBox.attr('checked', '');
});

We also can add another functionality such as delete checked row or etc. Just play around with jQuery function and happy coding ;)

 

This Post Tags :

Bookmark Post :

Save on Delicious
  • It’s nice, I really like it. One thing though…when I went to go try the demo I clicked the actual check box and that didn’t work. I understand that it works when you click on the row, but if I were to implement this into a website it might not be the best thing, usability wise, for visitors.

  • @Ashley : Thanks for noticing :)
    To make it works i’ve added click function to the checkbox itself.

  • Wow! This was what I was looking for. Thanks.

    One thing from me also… I am unable to select all of the checkboxes with the one at top. Though I can deselect all. :)

  • Try this you will see the results…

    $(document).ready(function() {
    $(“#detailsTable thead tr th:first input:checkbox”).click(function() {
    var checkedStatus = this.checked;
    $(“#detailsTable tbody tr td:first-child input:checkbox”).each(function() {
    this.checked = checkedStatus;
    });
    });
    $(“#detailsTable”).selectAllRows({ column: ‘first’ });

    });

  • and how to change it if the checkbox is in the last td?

  • Here is a another solution to try to fix the “check-all/uncheck-all” problem:

    $(‘table tr’).click(function(event) {
    if (event.target.type !== ‘checkbox’) {
    $(‘:checkbox’, this).trigger(‘click’);
    }
    });

    $(‘.check-all’).click(function() {
    checkBox = $(‘tbody tr’).children(‘td’).children(‘input[type=checkbox]‘);
    if($(this).attr(‘checked’))
    checkBox.attr(‘checked’, ‘checked’);
    else
    checkBox.attr(‘checked’, ”)
    });