简体   繁体   中英

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

 $('#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 /> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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