简体   繁体   中英

Flip toggle switch (jQuery) on change not firing

I need to fire an event (which sends POST data to an external script) when the state of a toggle switch changes, but I cannot even get the most basic example to work...

Can someone please tell me what I am doing wrong?

HTML:

<label for="flipswitch">Option:</label>
<select name="flipswitch" id="flipswitch" data-role="slider">
    <option value="off">Off</option>
    <option value="on">On</option>
</select>`

JavaScript (in the <head> section):

<script>

    $('#flipswitch').change(function(){
        console.log("flipswitch");
    });
</script>

The code works for me. Are you sure you're looking at the console output? Do you have the code in the $('document').ready(function() {

)};

The problem you are experiencing is that at the execution time of script, there is no element with the specified id. There are several ways how to overcome this problem.

<script>

    $(function() {
        $('#flipswitch').change(function(){
            console.log("flipswitch");
        });          
    });
</script>

or you may simply move the script tag from head tag to the bottom of body tag and it will work as well.

$("#flipswitch").on("change", function(e){
    console.log("flipswitch");
});

Could be because the .change is deprecated in favor of .on()

DEMO: http://jsfiddle.net/naUmA/13/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM