I'm working with jQuery Mobile, and I save some settings in a cooki开发者_StackOverflowe. 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?
After you change the value of the switch you have to refresh it for the animation to toggle:
$('#Switch2').val('on').slider("refresh");
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
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>
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
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).
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!)");
}
精彩评论