【问题标题】:How to make an unchecked checkbox value 0 and checked value of 1?如何使未选中的复选框值为 0,选中的值为 1?
【发布时间】:2021-07-06 05:41:54
【问题描述】:

我正在制作一个简单的注册表单,其中包含一个声明,询问用户是否已阅读条款和条件,但是当我控制台记录复选框的值时,它不会根据它是否被选中而改变。我该怎么做呢?我见过其他人问过这个问题,但他们使用的是像 jQuery 这样的 JS 库,而我没有使用,所以你如何仅使用基本的 JS 和 HTML 来区分选中和未选中的值

<div class="item">
          <input type="checkbox" id="checkbox" value="1">
          <label>I accept the <a id="termsLink" href="https://imgur.com/5lXi3Lc" target="_blank">Terms and Conditions</a></label>
        </div>

这是包含复选框的 div。

【问题讨论】:

标签: javascript html input checkbox


【解决方案1】:

您可以添加事件处理程序 onClick 以实现此目的:

function handleClick(cb) {
  cb.value = cb.checked ? 1 : 0;
  console.log(cb.value);
}
<div class="item">
          <input type="checkbox" id="checkbox" value="1" onclick='handleClick(this);'>
          <label>I accept the <a id="termsLink" href="https://imgur.com/5lXi3Lc" target="_blank">Terms and Conditions</a></label>
        </div>

【讨论】:

    【解决方案2】:

    你可以使用.checked方法:

    var checkBox = document.getElementById("checkbox");
    if(checkbox.checked){
          console.log("checked");
    }
    else{
         console.log("unchecked");
    }
    

    【讨论】:

      【解决方案3】:

      您需要测试.checked 属性。要将其转换为整数,可以使用按位或运算符。

      document.getElementById('checkbox').addEventListener('change', function(e){
        let checked = this.checked;
        console.log(checked);
        console.log(checked | 0);
      });
      <div class="item">
        <input type="checkbox" id="checkbox">
        <label>I accept the <a id="termsLink" href="https://imgur.com/5lXi3Lc" target="_blank">Terms and Conditions</a></label>
      </div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-02-07
        • 1970-01-01
        • 1970-01-01
        • 2021-10-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多