How can I work out if 'this' checkbox has been checked using the this command?
I have the following but not sure how to implement this (so it only checks the single checkbox selected rather than all on the page
if ($('input[type="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.
Use the target. checked property on the event object to check if a checkbox is checked in React, e.g. if (event. target. checked) {} .
prop() and is() method are the two way by which we can check whether a checkbox is checked in jQuery or not. prop(): This method provides an simple way to track down the status of checkboxes. It works well in every condition because every checkbox has checked property which specifies its checked or unchecked status.
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);
What about this?
if($(this).is(':checked'))
Presumably you mean this
in the context of an event handler... In which case, just test the checked
property:
$('input[type="checkbox"]').click(function() {
if (this.checked) {
// checkbox clicked is now checked
}
});
Note that you can do the same with the following methods:
$(this).is(':checked')
$(this).prop('checked')
However, this.checked
avoids creating a new jQuery object, so is far more efficient (and quicker to code). is
is the slowest: it takes twice as long as prop
and approximately 100 times as long as the simple property lookup.
jsPerf comparison between this techniques
You need to use the ID selector. The input[type="checkbox"] selector will return 'all checkboxes.
if ($('#Checkbox1').is(':checked'))
where Checkbox1 is the ID of the checkbox
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