如何使未选中的复选框值为 0 并选中值为 1?
How to make an unchecked checkbox value 0 and checked value of 1?
我正在制作一个简单的注册表单,其中包含一个声明,询问用户是否已阅读条款和条件,但是当我控制台记录复选框的值时,它不会根据是否选中而改变。我该怎么做呢?我见过其他人问过这个问题,但他们使用的是像 jQuery 这样的 JS 库,我没有使用它,所以你如何仅使用基本 JS 和 HTML[ 来区分已检查和未检查的值? =11=]
<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
属性。要将其转换为整数,可以使用按位或运算符。
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>
我正在制作一个简单的注册表单,其中包含一个声明,询问用户是否已阅读条款和条件,但是当我控制台记录复选框的值时,它不会根据是否选中而改变。我该怎么做呢?我见过其他人问过这个问题,但他们使用的是像 jQuery 这样的 JS 库,我没有使用它,所以你如何仅使用基本 JS 和 HTML[ 来区分已检查和未检查的值? =11=]
<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
属性。要将其转换为整数,可以使用按位或运算符。
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>