[英]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.