13

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

summu
  • 388
  • 2
  • 7
  • 25

5 Answers5

31

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
    }
});
Himanshu Upadhyay
  • 6,558
  • 1
  • 20
  • 33
16

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.

executable
  • 3,365
  • 6
  • 24
  • 52
4
$("#togBtn").on('change', function() {
        if ($(this).is(':checked')) {
            $(this).attr('value', 'true');
            alert($(this).val());
        }
        else {
           $(this).attr('value', 'false');
           alert($(this).val());
        }
    });
hitesh makodiya
  • 439
  • 2
  • 13
3

if want to access table row

$('body').on('change', '#statusSwitch', function () {    
    if ($(this).is(':checked')) {
    ****Your logic*****
    }
    else {
        ***Your logic***
    }
});
Dave
  • 3,073
  • 7
  • 20
  • 33
0
$("#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'));
}
לבני מלכה
  • 15,925
  • 2
  • 23
  • 47