Select all checkboxes with Alpine.js

UPDATED 2021-12-03

Using the document.querySelectorAl to manipulate the DOM directly is not a good way to do this. Instead have array which contains all the availabe items.

A short simple snippet on how to select/deselect all checkboxes on a page. Just binding all boxes to a value will not work because of the two-way bindings. If you click on one check then the state will fall out of sync. Instead I chose to have a property to keep track of the state and change the checkboxes’ state accordingly via class names (in a jQuery-ish way) ;-).


<script>
      var allInvoices = @json($job->invoices->pluck('invoice_id'));
</script>

<div x-data="{
	selectAll: false,
	toggleAllCheckboxes() {
		this.selectAll = !this.selectAll

		// GOOD uses bindings
        this.selectAll ? this.invoices = window.allInvoices :  this.invoices = [];

		// BAD This does not work, messes with the bindings
		checkboxes = document.querySelectorAll('.selectable');
		[...checkboxes].map((el) => {
			el.checked = this.selectAll;
		})
	}
}">
        
  
<thead>
	<th class="text-left">
		<input @click="toggleAllCheckboxes()" 
			type="checkbox" 
			x-bind:checked="selectAll" 
			autocomplete="off"
	>
  </th>
  ....
</thead>
<tbody>
	<tr>
		<td>
			<input class="selectable" type="checkbox" name="id[]" value="1">
		</td>
  	....