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.
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.
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.
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.
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.
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 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