Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - Checkbox on-change event doesn't fire if checked using JQuery

Tags:

html

jquery

I have this Check All function which check all check boxes. I use JQuery to do that.

But I also have this on change function that toggle a class to the wrapper div:

$('input[type="checkbox"]').on('change', function(){     $(this).closest('div').toggleClass('highlight'); }); 

That function runs when I click the Checkbox, but not if I click Check all.

Is there any way to manually fire an event using JQuery? Or is there better solution?

Thanks

EDIT:

Here's the simplified HTML:

<a id="check_all">Check All</a> <div>     <input type="checkbox" name="cb" value="abc">ABC<br> </div> <div>     <input type="checkbox" name="cb" value="pqr">PQR<br> </div> <div>     <input type="checkbox" name="cb" value="xyz">XYZ<br> </div> 

Here's the JSFiddle

http://jsfiddle.net/DarcFiddle/d4VTh/

like image 693
hrsetyono Avatar asked Jun 03 '13 08:06

hrsetyono


People also ask

How do I check if a checkbox is checked in an event?

addEventListener('click', event => { if(event. target. checked) { alert("Checkbox checked!"); } });

How can I check checkbox checked in jQuery?

filter(':checked'). length; $('#count-checked-checkboxes'). text(countCheckedCheckboxes); $('#edit-count-checked-checkboxes'). val(countCheckedCheckboxes); }); });

Which event is fired when a checkbox is selected?

There are two events that you can attach to the checkbox to be fired once the checkbox value has been changed they are the onclick and the onchange events.


2 Answers

After click check all you should call change() event like this

$(document).ready(function(){     $("input[type='checkbox']").on('change', function(){         $(this).closest('div').toggleClass('highlight');     });      $("#check_all").on('click', function(){         $("input[type='checkbox']").prop('checked', true).change();     }); }); 
like image 135
visnu Avatar answered Oct 14 '22 16:10

visnu


This will trigger the change event, but only after you bind it first.

$('input[type="checkbox]').trigger('change'); 
like image 22
woutr_be Avatar answered Oct 14 '22 18:10

woutr_be