Home > Net >  Laravel Count Checked Checkbox Real-Time
Laravel Count Checked Checkbox Real-Time

Time:11-03

Good Days Guys. How do I count the checked checkbox in real-time? I have these button labeled Transfer Students and I want the user to know how many students are currently checked (since our classrooms are size sensitive)

  <button   
    wire:click="editModal()"
        class="bg-blue-500 hover:bg-blue-300 text-white font-bold py-2 px-4 border-b-4 border-blue-700 hover:border-blue-500 rounded">
        Transfer Student($count of selected students) 
      </button>

 <input type="checkbox" wire:model="selectedStudents.{{ $stud->id }}">

CodePudding user response:

I would alter how you're tracking your selectedStudents to make things a little easier.

Your current implementation of selectedStudents.{{ $stud->id }} results in an array where the key is the student id and the value is either also the student id (when selected) or false when unselected. Selecting and then unselecting a checkbox does not remove the array element, instead its value is set to false.

So instead, if you bind Livewire to your selectedStudents array and then use the value attribute of the input element, you can achieve a similar but simplified result.

<input type="checkbox" wire:model="selectedStudents" value="{{ $stud->id }}" />

The result of the above is a numerically indexed array where the value is the student id. When you select a checkbox, an element is added to selectedStudents and when you unselect a checkbox it is removed.

The benefit of this is that you can now simply use count($selectedStudents) to get the number of students selected.

{{ count($selectedStudents) }} have been selected
  • Related