Если вы новичок в Jquery или хотите изучить некоторые основы, прежде чем приступить к этому руководству, я должен порекомендовать вам ознакомиться с разделами learn-javascript-from-scratch и jquery-step-by-step-tutorial-for-beginners.

Итак, здесь я собираюсь показать, как это можно сделать с помощью Jquery. Это может стать удобным, и я также использовал его во многих проектах, и он отлично работает для меня.

Итак, начнем.

ШАГ 1:

Прежде всего, вы должны добавить библиотеку jquery на свою страницу:

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>

ШАГ 2:

Создайте пустой файл HTML и поместите следующий код:

<body>
<div id="container">
    <div id="body">
        <div class="header" >Check/Uncheck all checkbox with Jquery</div>

            <table class="bordered" >
                <tr>
                    <th width="10%"><input type="checkbox" name="chk_all" class="chk_all"></th>
                    <th >Select All Items</th>
                </tr>
                <tr>
                    <td ><input type="checkbox" name="country_id" class="checkboxes" value="6" ></td>
                    <td > Item-1 </td>
                </tr>
                <tr>
                    <td ><input type="checkbox" name="country_id" class="checkboxes" value="7" ></td>
                    <td > Item-2 </td>
                </tr>
                <tr>
                    <td ><input type="checkbox" name="country_id" class="checkboxes" value="8" ></td>
                    <td > Item-3 </td>
                </tr>
                <tr>
                    <td ><input type="checkbox" name="country_id" class="checkboxes" value="9" ></td>
                    <td > Item-4 </td>
                </tr>
                <tr>
                    <td><input type="checkbox" name="country_id" class="checkboxes" value="10" ></td>
                    <td > Item-5 </td>
                </tr>
                <tr>
                    <td ><input type="checkbox" name="country_id" class="checkboxes" value="10" ></td>
                    <td > Item-6 </td>
                </tr>

            </table>

    </div>
</div>
</body>

ШАГ 3:

После завершения тега HTML добавьте код Javascript, включая тег script, следующим образом:

<script type="text/javascript">
    $(document).ready(function () {

        //To Check all checkbox
        $(".chk_all").click(function () {

            var checkAll = $(".chk_all").prop('checked');
            if (checkAll) {
                $(".checkboxes").prop("checked", true);
            } else {
                $(".checkboxes").prop("checked", false);
            }

        });

        // if all checkbox are selected, check the chk_all checkbox
        $(".checkboxes").click(function ()
        {
            if($(".checkboxes").length==$(".subscheked:checked").length)
            {
                $(".chk_all").attr("checked", "checked");
            }
            else
            {
                $(".chk_all").removeAttr("checked");
            }
        });

    });
</script>

Теперь все готово. Если вы обнаружите какую-либо проблему, проверьте полный исходный код, приведенный ниже:

Полный исходный код:

Index.html

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
    <link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="container">
    <div id="body">
        <div class="header" >Check/Uncheck all checkbox with Jquery</div>

            <table class="bordered" >
                <tr>
                    <th width="10%"><input type="checkbox" name="chk_all" class="chk_all"></th>
                    <th >Select All Items</th>
                </tr>

                <tr>
                    <td ><input type="checkbox" name="country_id" class="checkboxes" value="6" ></td>
                    <td > Item-1 </td>
                </tr>
                <tr>
                    <td ><input type="checkbox" name="country_id" class="checkboxes" value="7" ></td>
                    <td > Item-2 </td>
                </tr>
                <tr>
                    <td ><input type="checkbox" name="country_id" class="checkboxes" value="8" ></td>
                    <td > Item-3 </td>
                </tr>
                <tr>
                    <td ><input type="checkbox" name="country_id" class="checkboxes" value="9" ></td>
                    <td > Item-4 </td>
                </tr>
                <tr>
                    <td><input type="checkbox" name="country_id" class="checkboxes" value="10" ></td>
                    <td > Item-5 </td>
                </tr>
                <tr>
                    <td ><input type="checkbox" name="country_id" class="checkboxes" value="10" ></td>
                    <td > Item-6 </td>
                </tr>

            </table>

    </div>
</div>
</body>
</html>
<script type="text/javascript">
    $(document).ready(function () {

        //To Check all checkbox
        $(".chk_all").click(function () {

            var checkAll = $(".chk_all").prop('checked');
            if (checkAll) {
                $(".checkboxes").prop("checked", true);
            } else {
                $(".checkboxes").prop("checked", false);
            }

        });

        // if all checkbox are selected, check the chk_all checkbox
        $(".checkboxes").click(function ()
        {
            if($(".checkboxes").length==$(".subscheked:checked").length)
            {
                $(".chk_all").attr("checked", "checked");
            }
            else
            {
                $(".chk_all").removeAttr("checked");
            }
        });

    });
</script>

CSS:

html, body {
   margin:0;
   padding:0;
   height:100%;
}
body {
	border: 0;
	color: #000;
}

#body{
	width: 500px;
    margin: 0 auto;
    max-width: 100%;
	padding:20px 0 70px 0;
	height: 100%;
}

#container {
   min-height:100%;
   position:relative;
}

.header{
    font-size: 25px;
    text-align: center;
    background-color: #d0dafd;
}
table {
    *border-collapse: collapse;
    border-spacing: 5px;
    width: 100%;
}

.bordered {
    border: solid darkgoldenrod 3px;
    box-shadow: 0 1px 1px darkgoldenrod;
}

.bordered td {
    padding: 10px;
    border-bottom: 2px solid #d0dafd;

}
.bordered th {
    padding: 10px;
    border-bottom: 2px solid darkgoldenrod;
    background-color: #eee;
    border-top: none;
    text-align:center;
}

.bordered tbody tr:nth-child(even) {
	background: #eeeeee;
	border:1px solid #000;

}
.bordered tbody tr:hover td {
	background: #d0dafd;
	color: #FF0000;
}
tr td {
    text-align: center;
}

Вывод:

Спасибо за прочтение.

Дайте мне знать. Если у вас возникнут какие-либо трудности, пожалуйста, не стесняйтесь комментировать ниже, мы рады помочь вам. если у вас есть какие-либо предложения обратной связи, пожалуйста, сообщите нам, комментируя.

Не забудьте поделиться этим уроком с друзьями в Facebook и Twitter.