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.
Try with
if($(this).parent().find('input').is(':checked')) {
something();
}
This works if there's only one checkbox.
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)
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") ){}
});
This also works if you know the id of the input html element:
if($('input#element_id_name:checked').length>0) {
//your code here.
}
If you know the ID, just use:
if ($("#myCheckBox").is(":checked")) {
}
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()
精彩评论