简体   繁体   中英

How to make an unchecked checkbox value 0 and checked value of 1?

I'm making a simple registration form with a declaration asking if the user has read the terms and conditions but when I console log the value of the checkbox it doesn't change depending on if it's checked or not. How do I do this? I've seen other people ask the question but they're using JS libraries like jQuery which I'm not using so how do you differentiate the value from checked and unchecked just using basic JS and 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>

This is the div containing the checkbox.

You can add an event handler onClick in order to achieve this:

 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>

You can use the .checked method:

var checkBox = document.getElementById("checkbox");
if(checkbox.checked){
      console.log("checked");
}
else{
     console.log("unchecked");
}

You need to test the .checked property. To convert it to an integer, you can use the bitwise OR operator.

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM