[英]How to make an unchecked checkbox value 0 and checked value of 1?
我正在制作一个带有声明的简单注册表单,询问用户是否已阅读条款和条件,但是当我控制台记录复选框的值时,它不会根据是否选中而改变。 我该怎么做呢? 我见过其他人问这个问题,但他们正在使用像 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。
您可以添加事件处理程序 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>
您可以使用.checked
方法:
var checkBox = document.getElementById("checkbox");
if(checkbox.checked){
console.log("checked");
}
else{
console.log("unchecked");
}
您需要测试.checked
属性。 要将其转换为 integer,您可以使用按位 OR 运算符。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.