【问题标题】:i want to check all my checkbox from one checkbox using laravel 8 mvc我想使用 laravel 8 mvc 从一个复选框中检查我的所有复选框
【发布时间】:2021-09-02 04:31:00
【问题描述】:

我想选中第一个 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>

【问题讨论】:

    标签: php laravel laravel-blade laravel-8


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 嘿!好的答案,我花时间编辑您的代码,只是删除了 if-else 并用 $(this).is(":checked") 替换了该布尔值,因为它在更少的代码行(并且没有重复代码)中是相同的结果。希望你不介意...
    • 谢谢@matiaslauriti
    • 我可以在不使用 jquery 的情况下使用我的控制器吗?因为在我检查完所有内容后,我将执行删除该行的功能,并且我想使用我理解的语言
    【解决方案2】:

    试试这个代码 -

    <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>
    

    【讨论】:

    • 嘿!好的答案,我花时间编辑您的代码,只是删除了 if-else 并用 e.checked 替换了该布尔值,因为它在更少的代码行(并且没有重复代码)中是相同的结果。希望你不介意...
    猜你喜欢
    • 2021-11-11
    • 1970-01-01
    • 2020-05-12
    • 1970-01-01
    • 1970-01-01
    • 2015-08-25
    • 2013-05-08
    • 2012-12-12
    • 1970-01-01
    相关资源
    最近更新 更多