4

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

 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>
4

4 回答 4

12

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

function UncheckAll(){ 
      var w = document.getElementsByTagName('input'); 
      for(var i = 0; i < w.length; i++){ 
        if(w[i].type=='checkbox'){ 
          w[i].checked = false; 
        }
      }
  } 
于 2012-09-11T06:41:14.863 回答
6

我没有看到您的代码试图取消选中这些框。你只是想专注于一个元素。

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);
});
于 2012-09-11T06:41:02.583 回答
6

你应该试试

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);
});
于 2012-09-11T06:41:27.597 回答
1

展示新技术的新答案。Vanilla 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 标准的一部分——有关浏览器兼容性,请参见此处

于 2015-06-30T21:24:42.533 回答