Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the switch toggle state(true/false) in javascript

I have a switch toggle which has following code, following one of the StackOverflow questions I did similarly

Here's How to add the text "ON" and "OFF" to toggle button

 <label class="switch">
 <input type="checkbox" id="togBtn" value="false" name="disableYXLogo">
 <div class="slider round"></div>
 </label>

and in css i am disabling input checkbox

.switch input {display:none;} then how would I get the true/false value of that switch toggle button. I tried this but it doesn't work for me

$("#togBtn").on('change', function() {
if ($(this).is(':checked')) {
    $(this).attr('value', 'true');
}
else {
   $(this).attr('value', 'false');
}});

How would I get the check/uncheck or true/false value in js for my toggle switch button

like image 514
summu Avatar asked May 01 '18 06:05

summu


2 Answers

The jquery if condition will give you that:

var switchStatus = false;
$("#togBtn").on('change', function() {
    if ($(this).is(':checked')) {
        switchStatus = $(this).is(':checked');
        alert(switchStatus);// To verify
    }
    else {
       switchStatus = $(this).is(':checked');
       alert(switchStatus);// To verify
    }
});
like image 163
Himanshu Upadhyay Avatar answered Nov 09 '22 22:11

Himanshu Upadhyay


You can achieve this easily by JavaScript:

var isChecked = this.checked;
console.log(isChecked);

or if your input has an id='switchValue'

var isChecked=document.getElementById("switchValue").checked;
console.log(isChecked);

This will return true if a switch is on and false if a switch is off.

like image 37
Vadim Malakhovski Avatar answered Nov 10 '22 00:11

Vadim Malakhovski