Change value of flip toggle dynamically with jQuery Mobile

二次信任 提交于 2019-12-22 04:22:24

问题


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?


回答1:


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

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



回答2:


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




回答3:


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>



回答4:


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




回答5:


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).




回答6:


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!)");
     }


来源:https://stackoverflow.com/questions/4263858/change-value-of-flip-toggle-dynamically-with-jquery-mobile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!