20

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.

1
  • Could you show your markup and some more context for this code? It's hard to know if the solution provided will be accurate from just this portion. Commented May 26, 2011 at 20:27

6 Answers 6

46

Try with

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

This works if there's only one checkbox.

Sign up to request clarification or add additional context in comments.

Comments

6

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)

Comments

5

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") ){}
});

Comments

4

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

if($('input#element_id_name:checked').length>0) {
  //your code here.
}

Comments

3

If you know the ID, just use:

if ($("#myCheckBox").is(":checked")) {  

}

Comments

1

Try doing this:

if ($(this).parent().find('input:checked').length > 0) {    
    $(this).find('.switch').attr('state','on');
} else {
    $(this).find('.switch').attr('state','off');
}

This assumes you have only 1 input within the scope of $(this).parent()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.