2015-02-23 78 views
0

我有以下代碼,主要來自How can I select all checkboxes from a form using pure JavaScript,它只是不工作。複選框選擇使用querySelectorAll不工作

的test.html

<html> 
    <head> 
    <script> 
    function select(){ 
     var inputs = document.querySelectorAll("input[type='checkbox']"); 
     for(var i = 0; i < inputs.length; i++) { 
      inputs[i].checked = true; 
     } 
    } 
    </script> 
    </head> 
    <body> 
     <form id="myId" name="myForm"> 
     <input type="checkbox" value="1"/> 1 
     <input type="checkbox" value="2"/> 2 
     <input type="checkbox" value="3"/> 3 
     <input type="button" onclick="select()" value="Select all"/> 
     </form> 
    </body> 
</html> 

單擊該按鈕不執行任何操作。 我必須在這裏做一些非常錯誤的事情,但我無法挑選出來。

+2

嘗試從改變'onclick'函數處理程序名'選擇()'一些不同的名稱,而不是與已知標籤衝突的......看到這個.. HTTP://的jsfiddle。淨/ t6b91d6m / – 2015-02-23 06:11:54

回答

3

的功能select嘗試任何其他名稱,放心你的代碼是好的。

2

嘗試......

<html> 
    <head> 
    <script> 
    function test(){ 
     var inputs = document.querySelectorAll("input[type='checkbox']"); 
     for(var i = 0; i < inputs.length; i++) { 
      inputs[i].checked = true; 
     } 
    } 
    </script> 
    </head> 
    <body> 
     <form id="myId" name="myForm"> 
     <input type="checkbox" value="1"/> 1 
     <input type="checkbox" value="2"/> 2 
     <input type="checkbox" value="3"/> 3 
     <input type="button" onclick="test()" value="Select all"/> 
     </form> 
    </body> 
</html> 
0

我建議你使用jQuery的做像這樣:

Live Demo

HTML

<ul class="chk-container"> 
<li><button id="selecctall">select all</button> 
<li><input class="checkbox1" type="checkbox" name="check[]" value="item1"> This is Item 1</li> 
<li><input class="checkbox1" type="checkbox" name="check[]" value="item2"> This is Item 2</li> 
<li><input class="checkbox1" type="checkbox" name="check[]" value="item3"> This is Item 3</li> 
<li><input class="checkbox1" type="checkbox" name="check[]" value="item4"> This is Item 4</li> 
<li><input class="checkbox1" type="checkbox" name="check[]" value="item5"> This is Item 5</li> 
<li><input class="checkbox1" type="checkbox" name="check[]" value="item6"> This is Item 6</li> 
<li><input class="checkbox2" type="checkbox" name="check[]" value="item6"> Do not select this</li> 
</ul> 

jQuery的

$(document).ready(function() { 
    $('#selecctall').mouseup(function(event) { //on click 
     if(document.activeElement.tagName ==='BUTTON') { // check select status 
      $('.checkbox1').each(function() { //loop through each checkbox 
       this.checked = true; //select all checkboxes with class "checkbox1"    
      }); 
     }else{ 
      $('.checkbox1').each(function() { //loop through each checkbox 
       this.checked = false; //deselect all checkboxes with class "checkbox1"      
      });   
     } 
    }); 

}); 

更簡單,更有效的方式

1

select是在HTMLInputElement上定義的本地方法,用於聚焦選定的輸入元素。
select

解決方案1:更改函數的名稱。
溶液2:嘗試onclick="window.select()" insted的的onclick="select()"