I tr...">

How to listen when checkbox is checked in jQuery

I need to know when any checkbox on the page is checked:

eg.

<input type="checkbox"> 

I tried this in jQuery

 $('input type=["checkbox"]').change(function(){ alert('changed'); }); 

But it didn’t work, any ideas?

+43
jquery
Jul 29 '11 at 20:39
source share
6 answers

Use the change() event and the is() test:

 $('input:checkbox').change( function(){ if ($(this).is(':checked')) { alert('checked'); } }); 

I updated above, due to my stupid jQuery dependency (in if ), when the DOM properties are equally suitable, as well as cheaper to use. The selector has also been changed so that it can be passed in those browsers that support it to the DOM method document.querySelectorAll() :

 $('input[type=checkbox]').change( function(){ if (this.checked) { alert('checked'); } }); 

For the sake of completion, the same can easily be done in simple JavaScript:

 var checkboxes = document.querySelectorAll('input[type=checkbox]'), checkboxArray = Array.from( checkboxes ); function confirmCheck() { if (this.checked) { alert('checked'); } } checkboxArray.forEach(function(checkbox) { checkbox.addEventListener('change', confirmCheck); }); 



Literature:

+78
Jul 29 '11 at 20:41
source share
 $('input:checkbox').live('change', function(){ if($(this).is(':checked')){ alert('checked'); } else { alert('un-checked'); } }); 

jsfiddle: http://jsfiddle.net/7Zg3x/1/

+18
Jul 29 '11 at 20:41
source share
 $('input:checkbox').change(function(){ if($(this).is(':checked')){ alert('Checked'); } }); 

Here is a demo

+10
Jul 29 '11 at 20:41
source share

try it

 $('input:checkbox').change(function(){ if(this.checked) alert('checked'); else alert('not checked'); }); 
+2
Jul 29 2018-11-11T00:
source share
 $("input:checkbox").change(function(){ alert($(this).val()); }); 

here is the fiddle http://jsfiddle.net/SXph5/

jquery change

+1
Jul 29 '11 at 20:41
source share
 $("input[type='checkbox']").click(function(){ alert("checked"); }); 

Only regular .click will do.

0
Jul 29 '11 at 20:41
source share