Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if 'this' checkbox is checked

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')
like image 742
Zabs Avatar asked Jan 13 '12 12:01

Zabs


People also ask

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 do you check if checkbox is checked or not 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) {} .

Which method is used to check the status of checkbox?

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.

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);


3 Answers

What about this?

if($(this).is(':checked')) 
like image 157
devnull69 Avatar answered Sep 28 '22 10:09

devnull69


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

like image 22
lonesomeday Avatar answered Sep 28 '22 12:09

lonesomeday


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

like image 32
robasta Avatar answered Sep 28 '22 10:09

robasta