As I didn't find any question asked before, on how to toggle checkbox on click of a table row, so I would like to share my approach to this...
click(function() { $(this). parent('tr'). find('input'). trigger('click'); });
Using jQuery, we first set an onclick event on the button after the document is loaded. In the onclick event, we created a function in which we first declared an array named arr. After that, we used a query selector to select all the selected checkboxes. Finally, we print all the vales in an alert box.
You can do this: var isChecked = $("#rowId input:checkbox")[0]. checked; That uses a descendant selector for the checkbox, then gets the raw DOM element, and looks at its checked property.
In order to select the checkbox of a row inside the table, we will first check whether the type
attribute
of the element we are targetting is not a checkbox if it's not a checkbox than we will check all the checkboxes nested inside that table row.
$(document).ready(function() { $('.record_table tr').click(function(event) { if (event.target.type !== 'checkbox') { $(':checkbox', this).trigger('click'); } }); });
Demo
If you want to highlight the table row on checkbox
checked
than we can use an if
condition with is(":checked")
, if yes than we find the closest tr
element using .closest()
and than we add class to it using addClass()
$("input[type='checkbox']").change(function (e) { if ($(this).is(":checked")) { //If the checkbox is checked $(this).closest('tr').addClass("highlight_row"); //Add class on checkbox checked } else { $(this).closest('tr').removeClass("highlight_row"); //Remove class on checkbox uncheck } });
Demo
This question was useful to me but I had an issue with the previous solution. If you click on a link in a table cell, it will trigger the checkbox toggle. I googled this and I saw a proposition to add a event.stopPropagation()
on the links of the table, like this:
$('.record_table tr a').click(function(event) { event.stopPropagation(); });
This solution was a bad idea because I had some jquery bootstrap popover on a link of the table...
So here is a solutions that fits me better. By the way as I'm using bootstrap 2.3, the highlight of the line is made by adding the "info" class to the tr. To use this code, you just need to add class="selectable"
to the table tag.
$(".selectable tbody tr input[type=checkbox]").change(function(e){ if (e.target.checked) $(this).closest("tr").addClass("info"); else $(this).closest("tr").removeClass("info"); }); $(".selectable tbody tr").click(function(e){ if (e.target.type != 'checkbox' && e.target.tagName != 'A'){ var cb = $(this).find("input[type=checkbox]"); cb.trigger('click'); } });
You will probably want to be more specific with the test condition, for exemple if you have other inputs in the row.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With