Maro Paro
Maro Paro

Reputation: 111

Can't get state of switch with javascript or jquery

I needed a switch button for a project of mine so I searched and found an easy solution at w3schools. The only issue is that I can't catch the state of the switch now. I created a function that will change the value of an input filed if the switch is toggled on or off.

var checker = false;

function poly_marker_ctrl(categ, t) {
    if (checker == false) {
        $("display_result").val('is checked');
        checker = true;
    } else {
        $("display_result").val('is unchecked');
        checker = false;
    }
}

But that doesn't seem to work. Here is the example on jsfiddle. Thanks for your time.

Upvotes: 0

Views: 623

Answers (1)

rushil
rushil

Reputation: 576

Try using this.

HTML section :

<div class="col-md-3">
    <label class="switch">
      <input type="checkbox">
      <div class="slider round"></div>
    </label>
    <input id="display_result" type="text" value="is unchecked" readonly>
<div>

In script :

 var switchButton = 'off';
 $(".slider").click(function(){
    if(switchButton == 'off'){
        switchButton = 'on';    
        $('#display_result').val('is checked');
    }else{
        switchButton = 'off';
        $('#display_result').val('is unchecked');
    }
});

And css same as you have shown in fiddle.It will work.

Upvotes: 1

Related Questions