Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if input is checked using jquery

How would I achieve this:

if($(this).parent().find('input:checked') == true)

{$(this).find('.switch').attr('state','on');}
else{$(this).find('.switch').attr('state','off');}

I know this is wrong but you get the idea I think :). If there is an input that is checked add state on if not state off.

like image 577
cmplieger Avatar asked May 26 '11 20:05

cmplieger


People also ask

How check input is checked or not in jQuery?

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 checkbox is checked true in jQuery?

When using jQuery and you wish to read whether a checkbox is checked or not. $('#checkboxid').is(':checked'); This will return true if the checkbox is checked and false if left unchecked.

How check if 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.

Is checked unchecked jQuery?

jQuery provides CSS like selectors which can make this kind of task trivial. If you remember, in HTML a checkbox is checked if the "checked" attribute is present and its value is not false, otherwise, it's unchecked.


4 Answers

Try with

if($(this).parent().find('input').is(':checked')) {
    something();
}

This works if there's only one checkbox.

like image 161
ezakto Avatar answered Sep 27 '22 19:09

ezakto


It is not necessarily wrong, but the selector returns all elements that apply to the condition. Therefore you have to check if the length is not 0:

if($(this).parent().find('input:checked').length)
like image 38
Daff Avatar answered Sep 27 '22 20:09

Daff


Supposign input[type=checkbox] = this, you can check it on the element itself.

Source: jQuery docs

$("input[type=checkbox]").change(function(){
    if ( this.checked ){}
    //or
    if ( $(this).prop("checked") ){}   
    //or
    if ( $(this).is(":checked") ){}
});
like image 44
Ma Jerez Avatar answered Sep 27 '22 20:09

Ma Jerez


This also works if you know the id of the input html element:

if($('input#element_id_name:checked').length>0) {
  //your code here.
}
like image 20
Code Buster Avatar answered Sep 27 '22 20:09

Code Buster