jqueryjquery-mobilejquery-mobile-popupjquery-mobile-flipswitch

jQuery Mobile - changing the flipswitch on click


I have a disabled flipswitch. When the flipswitch is clicked a popup appears asking the user if they're sure they want to change the flipswitch. If they click yes then they will have to reanswer several questions. I want to be able to change the flipswitch, answer questions, then go back and change the flipswitch again, reanswer questions... etc. For some reason when I click the flipswitch its working on the first click, but the second click it changes it from yes to no (or the other way around) and back. Its almost as if its recording how many times it was clicked.

Here is a fiddle to show the issue

Here is my code:

$("#US_toggle").click(function(){ //flipswitch is clicked
  $('#US_Popup').popup('open'); //popup is opened
  $('#US_changeYes').click(function(){
    if($("#US_toggle .ui-flipswitch").hasClass('ui-flipswitch-active')){                
      $("#US_toggle .ui-flipswitch").removeClass('ui-flipswitch-active');
    }else{
      $("#US_toggle .ui-flipswitch").addClass('ui-flipswitch-active');
    };
  });
});

Here is the html:

<div id="US_toggle" class="floatRight">             
    <select name="US_flipswitch" id="US_flipswitch" data-role="flipswitch" data-theme="c" disabled="disabled">
      <option value="off">No</option>
      <option value="on">Yes</option>
    </select>               
</div>

Solution

  • The problem is that you are adding the click code to the changeYes button every time the popup is launched. You should only add it once outside of the div click:

    Updated FIDDLE

    $("#US_toggle").click(function () {
        $('#US_Popup').popup('open');
    
    });
    
    $('#US_changeYes').click(function () {
        if ($("#US_toggle .ui-flipswitch").hasClass('ui-flipswitch-active')) {
            $("#US_toggle .ui-flipswitch").removeClass('ui-flipswitch-active');
        } else {
            $("#US_toggle .ui-flipswitch").addClass('ui-flipswitch-active');
        };
    });
    

    UPDATE: Instead of toggling the classes, it is probably better to toggle the select value and then refresh the flipswitch:

    $('#US_changeYes').click(function () {
        var curVal = $("#US_flipswitch").val();
        curVal == "off" ? $("#US_flipswitch").val("on").flipswitch("refresh") : $("#US_flipswitch").val("off").flipswitch("refresh");
    });
    

    New FIDDLE