提问者:小点点

如何在纯JavaScript中取消选中复选框?


以下是HTML代码:

<div class="text">
   <input value="true" type="checkbox" checked="" name="copyNewAddrToBilling"><label>

我想将该值更改为false。或者取消选中复选框。我想用纯JavaScript来实现,而不使用外部库(没有jQuery等)


共3个答案

匿名用户

<html>
    <body>
        <input id="check1" type="checkbox" checked="" name="copyNewAddrToBilling">
    </body>
    <script language="javascript">
        document.getElementById("check1").checked = true;
        document.getElementById("check1").checked = false;
    </script>
</html>

我已经在脚本元素中添加了语言属性,但它是不必要的,因为所有浏览器都将此作为默认设置,但它让人毫不怀疑这个示例所展示的内容。

如果要使用javascript访问元素,它有一组非常有限的getElement*函数。因此,您将需要养成为每个元素赋予唯一的id属性的习惯。

匿名用户

推荐使用,不带jQuery:

/code>一个ID并引用它。另外,如果希望复选框一开始就没有勾选,请删除/code>标记的部分。然后是:

document.getElementById("my-checkbox").checked = true;

纯JavaScript,没有元素ID(1):

var inputs = document.getElementsByTagName('input');

for(var i = 0; i<inputs.length; i++){

  if(typeof inputs[i].getAttribute === 'function' && inputs[i].getAttribute('name') === 'copyNewAddrToBilling'){

    inputs[i].checked = true;

    break;

  }
}

纯Javascript,没有元素ID(第二个):

document.querySelectorAll('.text input[name="copyNewAddrToBilling"]')[0].checked = true;

document.querySelector('.text input[name="copyNewAddrToBilling"]').checked = true;

请注意,以下浏览器支持方法:IE8+,Chrome4+,Safari3.1+,Firefox3.5+和所有移动浏览器。

如果元素可能丢失,您应该测试它是否存在,例如:

var input = document.querySelector('.text input[name="copyNewAddrToBilling"]');
if (!input) { return; }

使用jQuery:

$('.text input[name="copyNewAddrToBilling"]').prop('checked', true);

匿名用户

还有一种方法可以做到这一点:

//elem - get the checkbox element and then
elem.setAttribute('checked', 'checked'); //check
elem.removeAttribute('checked'); //uncheck