Toggle an image with input style hidden using jQuery Mobile Flip Switch on the same page

393 Views Asked by At

Detail: I need to toggle an image i.e. when the flip switch is on, it shows the image, and hides it when the value if off. The code is in a JS file.

$("#dashboard").append('<form><img src="../images/GREEN.png" style="display: none;" id="greenimage">Toggle Image<select id="flip" name="flip-select" data-role="flipswitch">'+
                    '<option>Off</option>'+
                    '<option>On</option>'+
                    '</select>'+
                '</img></form>');

$("#dashboard").trigger("create");          

                $('#flip').click(function() 
                        {

                            $("#yellowim").toggle('slow');
                        });

Putting checkpoints in the code shows that the CLICK function executes with the trigger event without even clicking the switch.

1

There are 1 best solutions below

0
ezanker On

You have a couple of problems.

First, IMG tag should close before the SELECT. Second, the ID you assigned to the image is 'greenimage', but you are trying to toggle 'yellowim'. Third, as you are adding the select dynamically, you should use event delegation to bind the event. Finally, on a select you use the change event not the click event.

If you are using jQM 1.4.x, you can use enhanceWithin() instead of trigger("create").

$("#dashboard").append('<form><img src="http://lorempixel.com/32/32/nature/1/" style="display: none;" id="greenimage" />Toggle Image<select id="flip" name="flip-select" data-role="flipswitch">' +
    '<option>Off</option>' +
    '<option>On</option>' +
    '</select>' +
    '</form>').enhanceWithin();

$("#dashboard").on("change", '#flip', function () {
    $("#greenimage").toggle('slow');
});

Here is a DEMO