【问题标题】:How to get the switch toggle state(true/false) in javascript如何在javascript中获取开关切换状态(真/假)
【发布时间】:2018-10-11 06:05:08
【问题描述】:

我有一个开关切换,它具有以下代码,遵循我类似做的 StackOverflow 问题之一

这里是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>

在 css 中我禁用输入复选框

.switch input {display:none;} 那么我将如何获得该开关切换按钮的真/假值。 我试过了,但它对我不起作用

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

如何在 js 中为我的切换开关按钮获取选中/取消选中或真/假值

【问题讨论】:

    标签: javascript jquery html checkbox


    【解决方案1】:

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

    【讨论】:

    • 代码隐藏了“输入复选框”,它只为
      ​​ 做 css 部分,所以上面的代码不适用于 $("#togBtn").on('改变',函数())
    • 我不明白你的评论。
    • 感谢它的工作,我正在使用 chrome 插件,所以它是回调函数的一部分
    • 感谢您接受我的回答。并投票赞成。
    • 你节省了我很多时间
    【解决方案2】:

    您可以通过 JavaScript 轻松实现:

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

    或者如果您的输入有 id='switchValue'

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

    如果开关打开则返回 true,如果开关关闭则返回 false。

    【讨论】:

      【解决方案3】:
      $("#togBtn").on('change', function() {
              if ($(this).is(':checked')) {
                  $(this).attr('value', 'true');
                  alert($(this).val());
              }
              else {
                 $(this).attr('value', 'false');
                 alert($(this).val());
              }
          });
      

      【讨论】:

        【解决方案4】:
        $("#togBtn").on('change', function() {
           if ($(this).attr('checked')) {
           $(this).val('true');
           }
          else {
           $(this).val('false');
        }});
        

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

        【讨论】:

          【解决方案5】:

          如果要访问表格行

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

          【讨论】:

          • 考虑在此处添加有关您要添加的其他答案的更多信息。
          猜你喜欢
          相关资源
          最近更新 更多
          热门标签