0

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.

daniula
  • 6,898
  • 4
  • 32
  • 49
ldeluca
  • 934
  • 3
  • 12
  • 25

2 Answers2

9

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');
}
Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
5
$("[name='pushtoggle']").bootstrapSwitch('state')
prasun
  • 7,073
  • 9
  • 41
  • 59
  • Thanks! This solution is good for setting too. `$('#mySwitch').attr('checked', true);` does nothing, `.bootstrapSwitch('state',true)` does. – Matteo Ferla Oct 19 '17 at 16:33