Javascript 如何在javascript中获取开关切换状态(真/假)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/50112451/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the switch toggle state(true/false) in javascript
提问by summu
I have a switch toggle which has following code, following one of the StackOverflow questions I did similarly
我有一个开关切换,其中包含以下代码,遵循我类似的 StackOverflow 问题之一
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
在 css 中我禁用输入复选框
.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
.switch input {display:none;}那么我将如何获得该开关切换按钮的真/假值。我试过这个,但它对我不起作用
$("#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
我如何在 js 中为我的切换开关按钮获取选中/取消选中或 true/false 值
回答by Himanshu Upadhyay
The jquery if condition will give you that:
jquery if 条件会给你:
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
    }
});
回答by Vadim Malakhovski
You can achieve this easily by JavaScript:
您可以通过 JavaScript 轻松实现这一点:
var isChecked = this.checked;
console.log(isChecked);
or if your input has an id='switchValue'
或者如果您的输入有 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.
如果开关打开,则返回 true,如果开关关闭,则返回 false。
回答by ???? ????
$("#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'));
}
回答by hitesh makodiya
$("#togBtn").on('change', function() {
        if ($(this).is(':checked')) {
            $(this).attr('value', 'true');
            alert($(this).val());
        }
        else {
           $(this).attr('value', 'false');
           alert($(this).val());
        }
    });

