So I am trying to create this quiz app in Laravel+Livewire.
I have this list-group of answers in HTML and whenever I click on an answer, I want it to save it as 'selected' in my array, so when the user submits the answer, I can directly save it in the database.
When I click submit ('Trimite raspunsul' in my language), I print the array of 'selectat' (which basically has a value of 0/1 based on if the users selected that answer or not) so I can verify it works correctly.
I click the answers and then 'submit': it shows that the selected answers are stored correctly: all indexes from 0-4 have value of 1.
The problem comes when I deselect all the answers: the value of the array starts messing up as you can see in this GIF:
Link to the GIF if you're unable to see it: https://i.imgur.com/Vx42aKj.gif
I mention that I also have a local javascript function to set the list-item to active when it's clicked upon so I don't have to wait for livewire to load it.
Here's my component code:
public $selectat = [0, 0, 0, 0, 0, 0, 0, 0, 0];
public function selectatRaspuns($id) {
if($this->selectat[$id] == 0) {
$this->selectat[$id] = 1;
}
else {
$this->selectat[$id] = 0;
}
/*
$this->dispatchBrowserEvent('selectatRaspuns', [
['idbuton' => $id],
]); */
}
public function submitRaspunsuri() {
dd($this->selectat);
}
and here is my blade:
<div class="list-group" wire:ignore>
@for ($i = 0; $i < $question->noA; $i++)
<button type="button" id="buton{{ $i }}" wire:click.prevent="selectatRaspuns({{$i}})"
@if($selectat[$i] == 1)
class="list-group-item list-group-item-action active"
@else
class="list-group-item list-group-item-action"
@endif
>
<b>{{ $litere[$i] }}.</b>
{{ $question->answer($i) }}
</button>
<script>
document.getElementById("buton"+@js($i)).addEventListener("click", function() {
ButonClicked(@js($i));
});
</script>
@endfor
</div>
<!-- and here's my Submit Answers button -->
<button type="button" class="btn btn-outline-primary" wire:click="submitRaspunsuri()">
<span>Trimite raspunsul</span>
</button>
What can I do to make the variables in the array to update correctly? Thanks a lot guys :)