How to programmatically switch a Zurb Foundation switch control in Chrome?

I would like to dynamically switch the state of a Zurb Foundation Switch control using javascript.

This is the 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 is here . I believe that they are based on this project .

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 - Enable - succeeds, but when I try to use $('#d').attr('checked','checked'); $('#d1').removeAttr('checked'); $('#d').attr('checked','checked'); $('#d1').removeAttr('checked'); , then it looks like CSS incorrectly selects the element as checked, and on-screen transitions - see how the last switch in the image below does not display the OFF state.

enter image description here

You can check these commands on the Switch page of the Zurb Foundation documentation; d refers to the fourth and largest switch that you see in the list at the top of the page.

+6
source share
2 answers

You can directly call the click function on an element.

 $("#d1").click(); // Switch ON 

The problem that you will encounter is that the identifier of the element changes, so it will be a little more complex, you can use smart selector elements to access the element. After changing the state of the elements, you will notice that the identifier has changed to:

 $("#d").click(); // Switch OFF 

Now you will switch back to the off state.

Greetings from Oliver.

+5
source

Alternatively, if you are not comfortable simulating a click, you can use jQuery # prop instead.

 $('input:not([checked])').prop('checked', true); $('input[checked]').prop('checked', false); 

Possible use case: inside the AJAX call error handler that was launched when clicked.

+2
source

All Articles