toggle checkbox with javascript

ぐ巨炮叔叔 提交于 2021-02-05 11:35:06

问题


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!


回答1:


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" />



回答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>



回答3:


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)



回答4:


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()



来源:https://stackoverflow.com/questions/55032741/toggle-checkbox-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!