使用javascript在页面加载时取消选中所有复选框

Uncheck all checkbox on pageload using javascript

本文关键字:复选框 取消 javascript 加载 使用      更新时间:2023-09-26

我正在使用以下代码,但它不起作用。如果有什么建议请告诉我。我希望在加载页面时取消选中所有复选框。我有以下代码,但它不起作用:

 window.onload = function abc() {
     document.getElementsByTagName('input')[0].focus();
 }
<tr>
    <td>
        <input type="checkbox" ID="cb1" value="29500" onclick="if(this.checked){ cbcheck(this) } else { cbuncheck(this)}" /> Laptop
    </td>
    <td>
        <a href="#" id="a1" onmouseover="showimage('a1','laptop1');"  >Show Image</a>
        <img src="Images/laptop.jpg" id="laptop1" alt="" style="display:none; width:150px; height:150px;" onmouseout="hideimage('a1','laptop1');" class="right"/>
    </td>
 </tr>
 <tr>
     <td>
          <input type="checkbox" ID="cb2" value="10500" onclick="if(this.checked){ cbcheck(this) } else { cbuncheck(this)}" /> Mobile
     </td>
     <td>
          <a href="#" id="a2" onmouseover="showimage('a2','mobile1');"  >Show Image</a>
          <img src="Images/mobile.jpg" id="mobile1" alt="" style="display:none; width:150px; height:150px;"   onmouseout="hideimage('a2','mobile1');" />
     </td>
</tr>

在页面加载事件上调用此函数

function UncheckAll(){ 
      var w = document.getElementsByTagName('input'); 
      for(var i = 0; i < w.length; i++){ 
        if(w[i].type=='checkbox'){ 
          w[i].checked = false; 
        }
      }
  } 

您应该尝试

window.onload = function(){
   var checkboxes = document.getElementsByTagName("INPUT");
   for(var x=0; x<checkboxes.length; x++)
   {
      if(checkboxes[x].type == "checkbox")
      {
          checkboxes[x].checked = false;
      }
   }
}

如果你能使用jQuery,你可以试试

$(function(){
    $('input[type=checkbox]').prop("checked", false);
});

我没有看到您的代码试图取消选中这些框。你只是想把注意力集中在一个元素上。

window.onload = function abc() {
    document.getElementsByTagName('input')[0].focus();
    var a = document.getElementById('form_name').getElementsByTagName('input');
    for (var i=0;i<a.length;i++) {
        if (a[i].type == 'checkbox') a[i].checked = false;
    }
}

我还建议您尝试JQuery。上面的代码在JQuery:中是这样的

$(document).ready(function(){
    $('#formID input[type=checkbox]').attr('checked',false);
});

展示新技术的新答案。香草JS现在在2015:

var list = document.querySelectorAll('input[type=checkbox]');
for (var item of list) {
    item.checked = false;
}

紧凑型单线变体:

for(var i of document.querySelectorAll('[type=checkbox]')) { i.checked = false; }

这是直接从NodeList MDN文档示例中得出的。querySelectorAll提供的列表是一个NodeListfor...of循环是一个用于迭代属性值的新语句,是2015 ECMAScript的一部分;6标准--请参阅此处了解浏览器兼容性。