这是我面临的小问题。我正在打印一个复选框列表,如果其中的 JSON 值为真,则在其中检查它们,如果 JSON 值为假,则不选中。 因此,如果复选框被选中,则 html 行是
<input id="to_be_shown_individually" type="checkbox" ${(this.to_be_shown_individually && 'checked')} value=> <br>
现在,我已经为用户提供了选中和取消选中 chekbox 的选项。因此,当他们取消选中该复选框时,其值始终保持为真。 首先看到这张图片,因为 chekbox 被选中所以我得到了 true,但是在我取消选中它们的第二次尝试中我仍然得到了 true。
所以当我使用
documen.getElementByID("to_be_shown_individually").value;
无论用户是否取消选中复选框,它总是说 true
最佳答案
复选框的值
始终可用。要确定它是否被选中,您需要使用 checked
属性:
document.querySelector('button').addEventListener('click', function() {
var checkbox = document.getElementById("to_be_shown_individually");
console.log(checkbox.value, checkbox.checked);
})
<input id="to_be_shown_individually" type="checkbox" checked value="foobar" />
<button>Get state</button>
关于javascript - 发送前更改复选框默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59211411/