skip to Main Content

This is small problem I am facing. I am printing a checkbox list in which they are checked if the JSON value coming inside them is true and unchecked if JSON value is false.
So if the checkbox is checked the line of html is

<input id="to_be_shown_individually" type="checkbox" ${(this.to_be_shown_individually && 'checked')} value=> <br>

Now , i have given option to user to check and uncheck chekbox . So when they uncheck the checkbox its value remains true always.
See this image in first as chekbox are checked so i get true, but in second attempt when i uncheck them i still get true .

so when i use

documen.getElementByID("to_be_shown_individually").value;

It always says true whther user have unchecked the checkbox

3

Answers


  1. The value of a checkbox is always available. To determine if it’s checked or not you need to use the checked property:

    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>
    Login or Signup to reply.
  2. Instead of

    document.getElementByID("to_be_shown_individually").value;

    Look for

    document.getElementByID("to_be_shown_individually").checked;

    this will give you a true or false response based on if the checkbox is checked

    Login or Signup to reply.
  3. html

     <input type="checkbox" id="chk">
    

    javascript code

    var checked = json value is true;
    $("#chk"). prop("checked", checked);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search