toggle checkbox with javascript

前端 未结 4 1816
南旧
南旧 2021-01-27 06:28

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


        
相关标签:
4条回答
  • 2021-01-27 06:48

    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>

    0 讨论(0)
  • 2021-01-27 06:52

    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)
    
    0 讨论(0)
  • 2021-01-27 07:01

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

    0 讨论(0)
  • 2021-01-27 07:10

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

    0 讨论(0)
提交回复
热议问题