Search code examples
javascriptjqueryjquery-mobileevent-handlingjquery-mobile-flipswitch

How to only fire event if flipswitch is manually switched


I've created an jQuery Mobile flipswitch like this

<select id="flip" data-role="flipswitch">
    <option value="animal">Lion</option>
    <option value="flower">Rose</option>
</select>

and I listen to changes on this flipswitch

$( document ).on( 'change', '#flip', function( e ) {
   console.log( 'changed' );
}

But I don't want the event to be triggered if I change the value of the flipswitch by

$( '#flip' ).val( 'flower' ).flipswitch( 'refresh' );

How do I check if a flipswitch has changed by interacting with it directly or setting a value and refreshing the flipswitch?

I've created an example of the unwanted behavior under this JSFiddle.


Solution

  • You need to use .on() to attach change event and .off() to remove it - before you bind it again - whenever you change the value dynamically.

    Wrap all your code in pagecreate event, it is equvilant to .ready().

    $(document).on("pagecreate", "#main", function () {
    
        /* change event handler */
        function flipChanged(e) {
            var id = this.id,
                value = this.value;
            console.log(id + " has been changed! " + value);
        }
    
        /* add listener - this will be removed once other buttons are clicked */
        $("#flip").on("change", flipChanged);
    
        $('#setlion').on('vclick', function (e) {
            $("#flip")
                .off("change") /* remove previous listener */
                .val('animal') /* update value */
                .flipswitch('refresh') /* re-enhance switch */
                .on("change", flipChanged); /* add listener again */
        });
    
        $('#setrose').on('vclick', function (e) {
            $("#flip")
                .off("change")
                .val('flower')
                .flipswitch('refresh')
                .on("change", flipChanged);
        });
    });
    

    Demo