0

I want to uncheck a checkbox using javascript. I have one button which just unchecks the box and works fine:

function clear() {
document.getElementById("check").checked = "";
}

I have another button that I want to check the box if not checked and uncheck if it is. Below doesn't uncheck the box. I can can switch the if statement and does works the opposite way. What's the problem?

function switchIt() {
if (document.getElementById("check").checked !== "checked") {
  document.getElementById("check").checked = "checked";
} else {
  document.getElementById("check").checked = "";
}

Thanks!

2

4 Answers 4

4

switch is a reserved word, use another one

function switchIt() {
  var box = document.getElementById("check");
  
  if (box.checked) {
    box.checked = false;
  } else {
    box.checked = true;
  }
}

setInterval(switchIt, 1000);
<input type="checkbox" id="check" />

Sign up to request clarification or add additional context in comments.

1 Comment

switch wasn't the actual name. Tried this and works perfectly so thanks @taki
2

Treat "checked" as a boolean, not as a string.

You can just invert it, as in

element = document.getElementById("check")
element.checked = !element.checked

A more featured example:

var $toggle = document.getElementById('toggle');
var $checkbox = document.getElementById('checkbox');



var toggle_checkbox = function() {
   $checkbox.checked = !checkbox.checked;
}

$toggle.addEventListener('click',toggle_checkbox);
<label>
  Checkbox:
  <input id="checkbox" type="checkbox" checked />
</label>
<button id="toggle">Toggle</button>

Comments

1

You need a boolean to do that.

Take a look at this pen:

https://codepen.io/anon/pen/jJyXgO

let checkbox = document.querySelectorAll('#check')[0]

setInterval(function() {
  checkbox.checked = !checkbox.checked
}, 1000)

Comments

0

I've never seen it done with a string "checked" before. Try with a boolean like:

function change() {
    if (document.getElementById("check").checked !== true) {
      document.getElementById("check").checked = true;
    } else {
      document.getElementById("check").checked = false;
    }
}

or easier

function change() {
    document.getElementById("check").checked = !document.getElementById("check").checked
}

Don't forget, switch is reserved, so use a different name, as I did with change()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.