我正在制作一个简单的注册表单,其中包含一个声明,询问用户是否阅读了条款和条件,但是当我在控制台上记录复选框的值时,它不会改变,这取决于它是否被选中。我该怎么做呢?我见过其他人问这个问题,但他们使用的是像jQuery这样的JS库,而我没有使用这些库,那么您如何仅使用基本的JS和超文本标记语言来区分选中和未选中的值
<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。
发布于 2021-04-11 00:05:54
您可以添加一个事件处理程序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>
发布于 2021-04-11 00:08:15
您可以使用.checked方法:
var checkBox = document.getElementById("checkbox");
if(checkbox.checked){
console.log("checked");
}
else{
console.log("unchecked");
}发布于 2021-04-11 00:08:22
您需要测试.checked属性。要将其转换为整数,可以使用按位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>
https://stackoverflow.com/questions/67036413
复制相似问题