'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



Solution 1:[1]

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
    }
});

Solution 2:[2]

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.

Solution 3:[3]

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

Solution 4:[4]

if want to access table row

$('body').on('change', '#statusSwitch', function () {    
    if ($(this).is(':checked')) {
    ****Your logic*****
    }
    else {
        ***Your logic***
    }
});

Solution 5:[5]

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

OR

$("#togBtn").on('change', function() {
     togBtn= $(this);
     togBtn.val(togBtn.prop('checked'));
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Himanshu Upadhyay
Solution 2 executable
Solution 3 hitesh makodiya
Solution 4 Dave
Solution 5 ???? ????