The checkbox does not change when you click on it.

I have a data table and I have one checkbox in a row for the user to select an item.

I use the following jQuery code to let the user select an item by clicking anywhere on the line:

$("tbody tr").click(function() { var checkbox = $(this).find(':checkbox'); checkbox.attr('checked', !checkbox.attr('checked')); }); 

The problem is that I click directly on the checkbox, nothing happens. i.e. if unchecked, it remains unchecked. If I clicked anywhere in the row, the checkbox will change the status.

I think jQuery code causes the action to execute twice. If I click on this flag, this flag will change, and then jQuery code will be executed to click on the line, and the flag will be changed. Not sure if this is really happening, but this is my hunch.

How can I check the box when the user clicks on the line and the same if they click directly on the checkbox?

+4
source share
4 answers

Check which element is clicked by checking event information. Then, if this is a check box, do not run the code. Otherwise, switch the verified attribute

 $("tbody tr").click(function(e) { e = e || event; var isCheckbox = $(e.target).is(":checkbox"); if (!isCheckbox) { var checkbox = $(this).find(':checkbox'); checkbox.attr('checked', !checkbox.attr('checked')); } }); 
+4
source

Tt is because the flag is in tbody tr. If you had to go through the code, you will notice that it has been checked, but then not marked by the click function. change the click function to exclude the etc that this check box contains.

 $("tbody tr td").click(function() { if ($("input:checkbox", $(this)).length) { //td contains check box do nothing } else { var checkbox = $(this).find(':checkbox'); checkbox.attr('checked', !checkbox.attr('checked')); } }); 
+3
source

You will catch the click event in the row. If the checkbox is set to TR, the event fires and you invert the "checked" attribute. One solution would be to place the event on each TD inside the TR, except for the TD containing this flag.

0
source

If the problem is that the event actually fires twice (and this seems like a fair assumption), then you should try using the event.preventDefault() and event.stopPropagation() event methods. They must stop the event from the flag itself.

0
source

Source: https://habr.com/ru/post/1310520/


All Articles