0

I am trying to create a button that when clicked replaces the value in the field true false. If we click the first time the field becomes true, if the second time the field becomes false. But I still can't get the results. The field only changes true.

Checkbox: <input type="checkbox" id="myCheck">

<button onclick="check()">Check Checkbox</button>

<script>
  function check() {
    var value = document.getElementById("myCheck");
    if (value = "false") {
      document.getElementById("myCheck").checked = true;
    } else {
      document.getElementById("myCheck").checked = false;
    }
  }
</script>
halfer
  • 19,824
  • 17
  • 99
  • 186
Maddie Graham
  • 2,019
  • 4
  • 25
  • 51
  • 2
    If you replace the ` – David Thomas Nov 28 '19 at 10:08

2 Answers2

2

Avoid inline handlers ("onclick"). You can simplify this using:

const checkUncheck = () => {
  const cb = document.querySelector("#myCheck");
  cb.checked = !cb.checked;
};

document.querySelector("button").addEventListener("click", checkUncheck); 
<input type="checkbox" id="myCheck" disabled>
<button>check/uncheck</button>
KooiInc
  • 119,216
  • 31
  • 141
  • 177
1

You need to check if the checked attribute of your checkbox is true or false.

Checkbox: <input type="checkbox" id="myCheck">

<button onclick="check()">Check Checkbox</button>

<script>
  function check() {
    var checkbox = document.getElementById("myCheck");
    if (checkbox.checked !== true) {
      checkbox.checked = true;
    } else {
      checkbox.checked = false;
    }
  }
</script>

Also, you can re-use the checkbox variable.

CodeF0x
  • 2,624
  • 6
  • 17
  • 28