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) ;-).

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

<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;
	<th class="text-left">
		<input @click="toggleAllCheckboxes()" 
			<input class="selectable" type="checkbox" name="id[]" value="1">