2016-12-14 71 views
0

我正在使用JQuery模板,並試圖添加一個全選複選框。在原始的ajax調用中,我將分類的每個ID添加到數組中。然後使用該數組選擇每個複選框。選擇所有複選框並切換輸入

這些複選框的默認行爲是在輸入框在選中時顯示在每個下方。我想這樣,全選複選框也會切換這些輸入。所以問題是,在檢查selectAll後,它會打開並關閉每次切換約5次。

我相信它與我的.each方法中嵌套的forloop有關,但不完全確定。

下面的代碼:

vendorClassifications = []; 
$('#selectall') 
     .click(function() { 
      if (this.checked) { 
       $('#step1data input:checkbox') 
        .each(function() { 
         this.checked = true; 
         for (var i = 0; i <= vendorClassifications.length; i++) { 
          if (vendorClassifications.hasOwnProperty(i)) { 
           $('#search_options_' + vendorClassifications[i]).toggle('blind'); 
          } 
         } 
        }); 
      } else { 
       $('#step1data input:checkbox') 
        .each(function() { 
         this.checked = false; 
         for (var i = 0; i <= vendorClassifications.length; i++) { 
          if (vendorClassifications.hasOwnProperty(i)) { 
           $('#search_options_' + i).toggle('blind'); 
          } 
         } 

        }); 
      } 
     }); 

回答

1

讓所有的複選框一次簡單得多比你想象的

// Gather up all the checkboxes 
var boxes = document.querySelectorAll("input[type=checkbox]"); 

而且,把他們都檢查也很簡單:

boxes.forEach(function(box){ 
    box.setAttribute("checked","checked"); 
}); 

並且,同時打開關聯元素的顯示意味着只添加一行:

boxes.forEach(function(box){ 
    box.setAttribute("checked","checked"); 
    box.nextElementSibling.style.display = "inline"; 
}); 

最後,追平了這一切的「全選」按鈕:

window.addEventListener("DOMContentLoaded", function(){ 
 
    
 
    // Get the Select All button 
 
    var btn = document.getElementById("btnSelect"); 
 
    
 
    // Gather up all the checkboxes 
 
    var boxes = document.querySelectorAll("input[type=checkbox]"); 
 
    
 
    // Set up click handler for checkboxes 
 
    boxes.forEach(function(box){ 
 
     box.addEventListener("change", function(){ 
 
     // Tie the checked property value to the display of the input next to it 
 
     this.nextElementSibling.style.display = this.checked ? "inline" : "none" ; 
 
     }); 
 
    }); 
 
    
 
    // Set up a click event handler for the button 
 
    btn.addEventListener("click", function(){ 
 
     // that loops the checkboxes and sets them all to checked 
 
     // and displays their neighbor 
 
     boxes.forEach(function(box){ 
 
     box.checked = true; 
 
     box.nextElementSibling.style.display = "inline"; 
 
     }); 
 
    }); 
 
    
 
});
input[type="text"] {display:none;}
<input type="checkbox" value="box1"><input type="text"> 
 
<input type="checkbox" value="box2"><input type="text"> 
 
<input type="checkbox" value="box3"><input type="text"> 
 
<input type="checkbox" value="box4"><input type="text"> 
 

 
<button id="btnSelect">Select All</button>

+0

感謝您成爲徹底的,我會插上電源,並讓你知道,如果我有任何其他問題! – Crumblenautjs