JavaScript - 切换“check all”复选框true / false

时间:2016-05-18 15:26:33

标签: javascript html

我正在尝试制作“切换复选框”功能,如下所示:

HTML代码:

<!-- "Check all" box -->
<input type="checkbox" name="check" id="cbx_00_00" onclick="selectbox( this.getAttribute( 'id' ));" />
<!-- the other ones -->
<input type="checkbox" name="check" id="cbx_00_01" />
<input type="checkbox" name="check" id="cbx_00_02" />
<input type="checkbox" name="check" id="cbx_00_03" />

JavaScript的:

function selectbox( eID ) {

    // instead of writing the element id in the html code,
    // i want to use "this.getAttribute( 'id' )"
    var c   = document.getElementById( eID );

    // now when we've got the id of the element,
    // let's get the required attribute.
    var box = c.getAttribute( 'name' );

    // set var i value to 0, in order to run "for i" loop
    var i   = 0;

    for(i; i < box.length; i++) {

        // now lets find if the main box (as box[0]) checked.
        // if returns true (it has been checked), then check all - else -
        // do not check 'em all.
        if(box[0].checked == true) {

            box[i].checked  = true;

        }
        else {

            box[i].checked  = false;

        }

    }

}

我不想要任何jQuery解决方案(即使它比纯js更容易),所以请避免建议。我想知道的是 - 如果我错了 - 您认为我应该怎么做才能解决这个问题? 非常感谢你。每个建议/小费都表示赞赏。

3 个答案:

答案 0 :(得分:0)

您的问题主要在于您正在迭代复选框名称,而不是带有该名称的复选框。

var box = c.getAttribute( 'name' );

现在,box等于"check",因此box[0]"c"box[1]"h"等。

您需要添加以下内容:

var boxes = document.getElementsByName(box);

然后迭代boxes

当然,此时,您可能也想重命名变量。

答案 1 :(得分:0)

根据变量box中的名称,您可以检查所有具有相同名称的框:

Array.prototype.forEach.call(document.getElementsByName(box), function(el) {
    el.checked = true;
});

Array.prototype.forEach.call用于循环getElementsByName返回的&#34;假数组&#34;因为NodeList类没有forEach }。)

我认为您可以通过不将元素的ID传递给您的函数来简化您的代码,而是直接将名称(selectbox(this.name))传递给您。另请注意,您可以使用.id.name访问ID和姓名,而不是使用getAttribute

答案 2 :(得分:0)

你可以简单。

HTML代码:

input type="checkbox" name="check" id="cbx_00_00" onclick="selectbox(this.getAttribute('name'));" />      
<input type="checkbox" name="check" id="cbx_00_01" />
<input type="checkbox" name="check" id="cbx_00_02" />
<input type="checkbox" name="check" id="cbx_00_03" />

使用Javascript:

function selectbox(eID) {       
        var checkBoxes = document.getElementsByName(eID);

        for (var i = 0; i < checkBoxes .length; i++) {
            if (checkBoxes[0].checked) {
                checkBoxes[i].checked = true;
            }
            else {
                checkBoxes[i].checked = false;
            }
        }
    }