I would like to to dynamically toggle the state of a Zurb Foundation Switch control using javascript.
This is a default Zurb Fondation Switch:
<!-- Default switch -->
<div class="switch">
<input id="d" name="switch-d" type="radio" checked>
<label for="d" onclick="">Off</label>
<input id="d1" name="switch-d" type="radio">
<label for="d1" onclick="">On</label>
<span></span>
</div>
Demo here. They're based on this project, I believe.
When I tried to change the state of the switch using jquery:
$('#d1').attr('checked','checked'); $('#d').removeAttr('checked'); // Switch ON
$('#d').attr('checked','checked'); $('#d1').removeAttr('checked'); // Switch OFF
it worked in Firefox but not in Chrome. In Chrome [v25 on OSX10.8.3], the first command - Switch ON - is successful but when I try to use $('#d').attr('checked','checked'); $('#d1').removeAttr('checked');
then it looks like the CSS is not correctly picking up the element as being checked and the display balks - see how the last Switch in the image below is not displaying the OFF state properly.
You can test these commands on the Switch page of the Zurb Foundation documentation; d
refers to the forth and largest switch you see in the list at the top of the page.
You can directly call the click function on the element.
$("#d1").click(); // Switch ON
The issue you will have is that the ID of the element changes so it will be slightly more tricky, you can use smarter selectors to get to the element. Once the elements state has changed you will note that the ID has changed to:
$("#d").click(); // Switch OFF
This will now toggle you back into an off state.
Cheers Oliver.
Alternatively, if you are uncomfortable with simulating a click, you can use jQuery's #prop instead.
$('input:not([checked])').prop('checked', true);
$('input[checked]').prop('checked', false);
Possible use case: inside an error handler of an AJAX call that was fired on click.
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