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?
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);
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.
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 .
Use the target. checked property on the event object to check if a checkbox is checked in React, e.g. if (event. target. checked) {} .
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:
Array.from()
.Array.prototype.forEach()
.document.querySelectorAll()
.EventTarget.addEventListener()
.:checked
.change()
.is()
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With