1

I have edit modal window with checkbox input in my laravel project. I want the value in checkbox checked when I open the edit form. Idk why it always checked the first value and not suit with the value from database like this picture:

enter image description here

HTML code:

<form action="" method="put" id="editForm">
    <div id="editModal">
        <div class="form-group row">
            <label for="roles" class="col-md-2 col-form-label">Roles</label>
            <div class="col-md-10 mt-2">
                <?php foreach ($roles as $value) : ?>
                    <div class="form-check-inline">
                        <label class="form-check-label">
                            <input type="checkbox" name="roles" id="editRoles" value="{{$value->id}}">
                            <?= $value->name ?>
                        </label>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
</form>

Ajax script:

<script>
    $('body').on('click', '#edit', function(e) {
        id = $(this).data('id');
        $.ajax({
            url: "users/" + id + "/edit",
            method: 'GET',
            success: function(result) {
                $('#editModal').show();
                for (let i = 0; i < result.roles.length; i++) {
                    $('#editRoles').prop('checked', result.roles[i]);
                }
                console.log(result.roles);
            }
        });
    });
</script>

controller:

public function edit(Request $request, $id){
    $decode_id = Hashids::decodeHex($id);
    $role = Role::findOrFail($decode_id);
    $permission = $role->getPermissionNames();

    if ($request->ajax()) {
        return response()->json(['role' => $role, 'permission' => $permission]);
    }
}

I also tried the solution from here with this code: $("#editModal input[type='checkbox']").prop('checked', result.roles[i]);

But it's checked all value! Anybody have solution for this?

man99
  • 47
  • 8
  • You have multiple `id="editRoles"` inside your loop - which is invalid, `id`s _must_ be unique. – brombeer Oct 10 '21 at 10:03
  • @brombeer hi, thank you for responding me! yes, I also got the "Found 2 elements with non-unique" warning in my console. but I still don't get it, how to make the unique id for my checkbox. – man99 Oct 10 '21 at 10:14
  • You can use a class instead of an id. Or add something incrementing, `editRoles1`, `editRoles2` etc – brombeer Oct 10 '21 at 16:38
  • @man99 did you find a solution to this? – stephen waweru99 Jul 22 '22 at 06:18

0 Answers0