Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Programatically Toggle a Zurb Foundation Switch Control, in Chrome?

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.

enter image description here

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.

like image 414
Oliver Lloyd Avatar asked Mar 25 '13 13:03

Oliver Lloyd


2 Answers

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.

like image 92
Matt Avatar answered Sep 26 '22 07:09

Matt


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.

like image 40
James Lim Avatar answered Sep 23 '22 07:09

James Lim