Jquery checkbox change event

Hi, I was wondering if there is an event for checkboxes that can be triggered by other code and not by the user ...

eg.

http://jsfiddle.net/DC3EH/

For the "Select All" checkbox, you should also automatically switch the "selected" class to switch the background color of the row.

I tried "edit" and "click" and it only starts by the user.

I commented on some code ... BTW I want to have many flags that switch certain flag classes, so I want to avoid a lot of ".closest ('tr'). AddClass ('selected');" and etc.

+4
source share
4 answers

It seems to work fine:

http://jsfiddle.net/DC3EH/20/

I used .change ()

+4
source

I'm not sure if this is what you need, but I realized that all <tr> should be changed to selected ones by checking the "Select all" checkbox. try http://jsfiddle.net/DC3EH/5/

0
source

Have you tried to fire the click event?

 .trigger("click") // for each checkbox 

Example: http://jsfiddle.net/ELTRd/1/

0
source

If you attach to a change event, you can trigger the click event in jquery, which will check the checkbox and in turn fire the change event:

 $(document).ready(function(){ $('#check_all').click(function(event) { $('[name^="checkbox"]').trigger("click"); }); $('[name^="checkbox"]').change(function(event) { console.log('a'); if ($(this).is(":checked")) { $(this).closest('tr').addClass('selected'); } else { $(this).closest('tr').removeClass('selected'); } }); });​ 

Updated script: http://jsfiddle.net/DC3EH/19/

The reason I switched to the change event instead of the click event is because jquery handles event triggering. When you start the click, it will call the event handler before it changes the state of the checkbox. Binding to a change ensures that your event is not triggered until the state changes.

0
source

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