简体   繁体   English

使用jQuery检查所有复选框

[英]Check all Checkboxes using jquery

I have button on my web page, and when this button is clicked I want to select all of the green check boxes in each row of my table. 我的网页上有一个按钮,单击此按钮后,我想选择表格每一行中的所有绿色复选框。

I am unsure of the logic for this and would appreciate some help 我不确定这样做的逻辑,希望能有所帮助

This is my table: 这是我的桌子:

$.each(JSON.parse(result), function (i, item) {
    var row = i + 1;

    $("#mainData").append(
        "<tr>" +
        "<td id='process_" + row + "'" + ">" + item.Process + "</td>" +
        "<td id='checks_" + row + "'" + ">" + item.Checks + "</td>" +
        "<td>" +

        "<div class='btn-group' data-toggle='buttons'" + ">" +

        "<label class='btn btn-success'" + ">" +
        "<input type='checkbox' name='colours' id='green_" + row + "'" + ">" +
        "<span class='glyphicon glyphicon-ok'" + "></span>" +
        "</label>" +

        "<label class='btn btn-warning'" + ">" +
        "<input type='checkbox' name='colours' id='yellow_" + row + "'" + ">" +
        "<span class='glyphicon glyphicon-ok'" + "></span>" +
        "</label>" +


        "<label class='btn btn-danger'" + ">" +
        "<input type='checkbox' name='colours' id='red_" + row + "'" + ">" +
        "<span class='glyphicon glyphicon-ok'" + "></span>" +
        "</label>" +


        "<label class='btn btn-default'" + ">" +
        "<input type='checkbox' name='colours' id='grey_" + row + "'" + ">" +
        "<span class='glyphicon glyphicon-ok'" + "></span>" +
        "</label>" +

        "</td>" +
        "<td><textarea id=" + "'" + "comments_" + row + "'" + "type='text' placeholder='' class='form-control input-md'/></td>" +

        "</tr>");
});

this is my select all button 这是我的全选按钮

 $('#SelectAll').click(function () {

    var rowCount = $('#mainData >tr').length;

    var i;

    for (i = 1; i <= rowCount; i++) {

        $("input:checkbox").prop('checked', $(this).prop("checked"));
    }
});

The best approach for this is to have a common class. 最好的方法是有一个普通的班级。 But in case you can't, you can use jQuery wildcard selector like [id^=green] This will select all elements with id starting with green 但是,如果不能,则可以使用[id^=green]类的jQuery通配符选择器。它将选择ID以green开头的所有元素

 $('#SelectAll').click(function() { //This will select all inputs with id starting with green $("input[id^='green']").prop('checked', $(this).prop("checked")); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="checkbox" id="SelectAll"> Select All Green<br /> <input type="checkbox" name='colours' id='green_1'>Green 1<br /> <input type="checkbox" name='colours' id='green_2'>Green 2<br /> <input type="checkbox" name='colours' id='blue_1'>Blue 1<br /> <input type="checkbox" name='colours' id='blue_2'>Blue 2<br /> <input type="checkbox" name='colours' id='red_1'>Red 1<br /> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM