Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vincent15000's avatar

I click on a checkbox and it's another checkbox that is checked

Hello,

I have this code with Livewire v2.

<div class="flex flex-col gap-2">
    @foreach ($etats as $etat)
        <div class="flex items-center" wire:key="{{ 'etats_selectionnes-'.$etat->id }}">
            <input
                type="checkbox"
                id="{{ 'etats_selectionnes-'.$etat->id }}"
                name="etats_selectionnes[]"
                value="{{ $etat->id }}"
                wire:model="etats_selectionnes"
                wire:key="{{ 'etats_selectionnes-input-'.$etat->id }}"
            >

            <label
                for="{{ 'etats_selectionnes-'.$etat->id }}"
                class="w-full whitespace-nowrap"
                wire:key="{{ 'etats_selectionnes-label-'.$etat->id }}"
            >
                {{ $etat->nom }}
            </label>
        </div>
    @endforeach
</div>

When I click on a checkbox, this one checked, but one or two other checkboxes uncheck at the same time.

So I have added the keys, but it doesn't work better.

I specify that the $etats_selectionnes array is initialized with an empty array, but the user can load a preselection (via a select/options field) to check automatically some checkboxes, and it seems that the problem occurs after having loaded a preselection.

For example, when selecting an option, in the Livewire class I execute this code.

$this->etats_selectionnes = [2, 3, 4, 8];

Any idea ?

Thanks for your help.

V

0 likes
1 reply
vincent15000's avatar
vincent15000
OP
Best Answer
Level 63

I have found the reason.

When selection an option, I initialize the selections states with integer, but via the form, when I click on a checkbox, the id of the state is added as a string (for example "2").

So I have replace $this->etats_selectionnes = [2, 3, 4, 8]; with $this->etats_selectionnes = ['2', '3', '4', '8']; and it works fine.

Please or to participate in this conversation.