2016-12-14 6 views
0

JQueryテンプレートを使用していますが、すべてを選択するチェックボックスを追加しようとしています。元のajax呼び出しでは、分類の各IDを配列に追加します。その後、その配列を使用して各チェックボックスを選択します。すべてのチェックボックスの選択と入力の切り替え

これらのチェックボックスのデフォルトの動作では、チェックボックスをオンにすると、入力ボックスがそれぞれ下に表示されます。私はすべてのチェックボックスを選択してこれらの入力を切り替えるようにしたいと思います。だから、問題は、selectAllをチェックした後、それぞれのトグルを約5回開閉するということです。

私は、それぞれの方法の中でネストされた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"); 
}); 

また、関連する要素の表示を同時にオンにすると、1行追加することを意味します。

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

関連する問題