复选框 - 在仅选中一个复选框时选中多个复选框

Checkbox - Getting multiple check boxes checked on checking only one

我正在尝试实现一个复选框来选中页面上的所有复选框。但是当我稍微更改代码时,它停止工作了。我想保留更改后的代码,但仍希望功能正常运行。请帮忙! * 如果有遗漏的标签,请忽略。除非我在编辑问题时出错,否则它是正确的。

   <script>     
    function toggle(source) {
        checkboxes = document.getElementsByName('qchecked[]');
        for(var i=0, n=checkboxes.length;i<n;i++){
            checkboxes[i].checked = source.checked;
        }
    }
</script>
<html> 
/* Code for the check box which when checked, checks all the checkbox. */
<input type='checkbox' class='css-checkbox' id='checkbox' onClick='toggle(this)'/>
<label for='checkbox' class='css-label lite-y-green'></label>



    /* Code for the check boxes which should be checked when the check box with id=checkbox is checked. 
I changed the code from INITIAL CODE to CHANGED CODE for some other purpose and the toggle stopped working. 
Now clicking on that one check box is not marking or un marking all the check boxes. */

    <!-- INITIAL CODE -->
    <input type='checkbox' id='yes_checkbox[$index]' class='css-checkbox' name='qchecked[]'/>
    <label for='yes_checkbox[$index]' class='css-label lite-y-green'></label>

    <!-- CHANGED CODE -->
    <input type='checkbox' id='yes_checkbox[$index]' class='css-checkbox' name='qchecked[$array6[qID]]'/>
    <label for='yes_checkbox[$index]' class='css-label lite-y-green'></label>
    </html>

试试这个..

<ul class="chk-container">
<li><input type="checkbox" id="selecctall"/> Selecct All</li>
<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>

$(document).ready(function() {
    $('#selecctall').click(function(event) {  //on click 
        if(this.checked) { // 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"                       
            });         
        }
    });

});

演示:https://jsfiddle.net/go1gL743/

因为你nameinputs不一样,你可以利用common class

checkboxes = document.getElementsByClassName('css-checkbox');

代替名称,给所有元素一个class,你应该使用

getElementsByClassName('your_class');