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?
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:
- JavaScript:
- JQuery:
$('input:checkbox').live('change', function(){ if($(this).is(':checked')){ alert('checked'); } else { alert('un-checked'); } }); jsfiddle: http://jsfiddle.net/7Zg3x/1/
$('input:checkbox').change(function(){ if($(this).is(':checked')){ alert('Checked'); } }); try it
$('input:checkbox').change(function(){ if(this.checked) alert('checked'); else alert('not checked'); }); $("input:checkbox").change(function(){ alert($(this).val()); }); here is the fiddle http://jsfiddle.net/SXph5/
$("input[type='checkbox']").click(function(){ alert("checked"); }); Only regular .click will do.