javascripthtmlinputcheckbox

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.


Solution

  • 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>