bootstrap switch checking checked status always returns false

ldeluca picture ldeluca · Jul 23, 2014 · Viewed 16.4k times · Source

I don't want to listen for the event of the switch being toggled, instead I want to use JavaScript to check it's current checked state.

<input type="checkbox" name="pushtoggle" state="true" data-role="none">

I have this simple JavaScript to check the checked value:

if ($('#pushtoggle').is(':checked')){ alert('checked'); } else { alert('not checked');}

No matter which state (on or off) the switch is set to I always get the alert that it is not checked.

I initialized the toggle switch using:

$("[name='pushtoggle']").bootstrapSwitch();

I also tried setting the checked attribute within the input tag. Nothing works to get me the correct state of the switch.

Answer

Claudio Redi picture Claudio Redi · Jul 23, 2014

You don't have any element with id = pushtoggle but you're using an id selector.

Try with this

if ($('[name="pushtoggle"]').is(':checked')){ 
  alert('checked'); 
} 
else { 
  alert('not checked');
}