Markus T.
Markus T.

Reputation: 91

Change value of flip toggle dynamically with jQuery Mobile

I'm working with jQuery Mobile, and I save some settings in a cookie. When the settings page is reloaded, I read the cookie to set all the values. I'm having trouble setting the flip toggle switch. Most elements just have to trigger the keyup or changed events, but I'm not sure how the flip toggles gets its value from the select box. Any ideas?

Upvotes: 9

Views: 28407

Answers (6)

Danmar
Danmar

Reputation: 11

An easy way to achieve this is to set the value, trigger the create and refresh. Afterwards you need to trigger the slidestop event to perform any action you bound to the slider. eg:

$('#mySlider').val('on').trigger('create').slider("refresh");
$('#mySlider').trigger('slidestop');

I've tested this on jQuery mobile ver. 1.3.0

Upvotes: 1

janesconference
janesconference

Reputation: 6473

This works for me:

 if (someCondition) {
         $('#slider').val('off');
     }
     else {
         $('#slider').val('on');
     }
     try {
         $('#slider').slider("refresh");
     }
     catch (err) {
         console.log ("Error occurred refreshing slider (probabily first time!)");
     }

Upvotes: 0

Byron Walker
Byron Walker

Reputation: 65

Using $('#slider2').val('on') will change the value, as it is supposed to. However, it does not add the CSS classes such as ui-btn-active to the option, nor does it remove that class from the the option. If you want to dynamically change the option, then you will have to take care of those parts manually (not jQuery Mobile).

Upvotes: 0

Chris D.
Chris D.

Reputation: 241

After you change the value of the switch you have to refresh it for the animation to toggle:

$('#Switch2').val('on').slider("refresh");

Upvotes: 24

naugtur
naugtur

Reputation: 16905

It looks like it's broken.

Go to the page: http://jquerymobile.com/demos/1.0a2/#docs/forms/forms-switch.html and use firebug console to run the following:

$('#slider2').val('on').trigger('keyup');

it changes the width of "on" part of the switch, but doesn't move the slider.

So the answer is: wait for the release of JQM :)

Bug issued here: https://github.com/jquery/jquery-mobile/issues/issue/676

Upvotes: 3

wyz
wyz

Reputation: 761

I think you can just set the value in select like normal HTML and flip toggle switch will pick up automatically. i.e.

<select name="slider" id="slider" data-role="slider">
  <option value="off">Off</option>
  <option value="on" selected="selected">On</option>
</select>

Upvotes: 0

Related Questions