我想使用 laravel 8 mvc 从一个复选框中检查所有复选框 我的刀片index.blade.php:

问题描述

我想检查 ID 为 checkAll 的第一个复选框,它会检查我所有的复选框,当我取消选中它时,它也会全部取消选中。

我的刀片index.blade.PHP

<body>
    <table class="table">
        <thead>
            <tr>
                <th scope="col">
                    <input type="checkBox" id="checkAll">
                </th>
                <th scope="col">id</th>
                <th scope="col">title</th>
                <th scope="col">Paragraph</th>
            </tr>
        </thead>
        @foreach ($categories as $categorie)
            <tbody>
                <tr>
                    <td>
                        <input type="checkBox" name="checkOne" value="{{$categorie->id}}">
                    </td>
                    <th scope="row">{{ $categorie->id }}</th>
                    <td>{{ $categorie->Title }}</td>
                    <td>{{ $categorie->Paragraph }}</td>
                    <form action={{ route('categorie.destroy',$categorie->id) }} method="POST">
                        @csrf
                        @method('DELETE')
                        <td>
                            <button class="btn btn-danger" type="submit">
                                delete
                            </button>
                    </form>
                    <button class="btn btn-warning"> <a href={{ route('edit',$categorie->id) }}>edit</a> </button>
                    </td>
                </tr>
            </tbody>
        @endforeach
    </table>

</body>

解决方法

如果您有多个同名复选框,则在循环中使用数组,如下所示:

<input type="checkbox" name="checkOne[]" value="{{ $categorie->id }}">

现在您需要使用 jQuery 来选择/取消选择复选框,使用以下代码:

$('#checkAll').change(function() { // main checkbox id
    $('input[name="checkOne[]"]').prop('checked',$(this).is(":checked"));
});
,

试试这个代码 -

<script type='text/javascript'>
    function checkAll(e) {
        const checkboxes = document.getElementsByName('checkOne');
        for (let i = 0; i < checkboxes.length; i++) { 
            checkboxes[i].checked = e.checked;
        }
    }
</script>