vendredi 28 octobre 2016

How can I bind a onclick event to a checkbox INSTEAD of a change event?

Here is the problem I have.

I'm making a control panel for some devices. Now the user can enable/toggle an on/off switch (checkbox) and so can a remote device. This is reflected in the database. However, I also want a confirm box whenever the user (NOT the device) toggles to enable the device (checkbox == checked). No confirmation box required for when the user disables (toggles off, checkbox==false) the device. I check the database every few seconds to see the state of device (since the device can turn itself on or off)

This is what I have so far (It doesn't work correctly. Nothing is sent to the database. on click doeesn't fire on user click in checkbox)

$(function() {
    $('#toggle').bootstrapToggle({
      on: TR_Toggle_On,
      off: TR_Toggle_Off
    });
    check_enable();

    function check_enable() {
        var timer = setInterval(function(result) {
            $.ajax({
                type: "get",
                url: "checkState.php",
                success: function(result) {
                    var enabled =parseInt(result);
                    if (enabled ===1) {
                        $( '#toggle').bootstrapToggle('on');
                    } else {
                        $( '#toggle').bootstrapToggle('off');
                    }
                }
            });
        }, 5000);
    }

    $('#toggle').on('click',function(){
        $('#toggle').change(function() {
            if ($('#toggle').prop('checked') ===true) {
                if(confirm("Sure?")){
                    $.ajax({
                    type: "get",
                    url: "setEnable.php",
                    data: "enable=1"
                    });
                }else{
                    $('#toggle').prop('checked',false);
                }
            } else {
                $.ajax({
                    type: "get",
                    url: "setEnable.php",
                    data: "enable=0"
                });
            }
        })
    })


})

How can I do this? When I try to register the on('click',func(){}) event, nothing fires. I assume it doesn't work for checkboxes? What am I doing wrong?




Aucun commentaire:

Enregistrer un commentaire