Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen to when a checkbox is checked in Jquery

Tags:

jquery

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

e.g.

<input type="checkbox"> 

I tried this in Jquery

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

But it didn't work, any ideas?

like image 989
Jordash Avatar asked Jul 29 '11 20:07

Jordash


People also ask

How check if checkbox is checked jQuery?

To check whether a Checkbox has been checked, in jQuery, you can simply select the element, get its underlying object, instead of the jQuery object ( [0] ) and use the built-in checked property: let isChecked = $('#takenBefore')[0]. checked console. log(isChecked);

How do you check if a checkbox is checked?

Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.

How can create checkbox click event in jQuery?

change() updates the textbox value with the checkbox status. I use . click() to confirm the action on uncheck. If the user selects cancel, the checkmark is restored but .

How do you check if a checkbox is checked react?

Use the target. checked property on the event object to check if a checkbox is checked in React, e.g. if (event. target. checked) {} .


1 Answers

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

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

I've updated the above, to the following, because of my silly reliance on jQuery (in the if) when the DOM properties would be equally appropriate, and also cheaper to use. Also the selector has been changed, in order to allow it to be passed, in those browsers that support it, to the DOM's document.querySelectorAll() method:

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

For the sake of completion, the same thing is also easily possible in plain 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); }); 

References:

  • JavaScript:
    • Array.from().
    • Array.prototype.forEach().
    • document.querySelectorAll().
    • EventTarget.addEventListener().
  • jQuery:
    • :checked.
    • change().
    • is().
like image 188
David Thomas Avatar answered Sep 22 '22 11:09

David Thomas