Skip to content

Instantly share code, notes, and snippets.

@ziadoz
Last active August 11, 2021 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ziadoz/55c475a014f1ba487598dc9a35669e2d to your computer and use it in GitHub Desktop.
Save ziadoz/55c475a014f1ba487598dc9a35669e2d to your computer and use it in GitHub Desktop.
Alpine JS - Checkboxes With All/None Toggle Links
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="http://unpkg.com/alpinejs" defer></script>
</head>
<body>
<!--
We have to use $refs because x-bind:checked updates the HTML not the prop.
@see: https://github.com/alpinejs/alpine/issues/520
-->
<div
x-data="{
toggle(checked) {
$refs.checkboxes
.querySelectorAll('input[type=checkbox]')
.forEach(c => c.checked = checked);
}
}"
>
<a href="#" @click.prevent="toggle(true)">All</a> | <a href="#" @click.prevent="toggle(false)">None</a>
<ul x-ref="checkboxes">
<li><label><input type="checkbox" value="a">A </label></li>
<li><label><input type="checkbox" value="b">B </label></li>
<li><label><input type="checkbox" value="c">C </label></li>
<li><label><input type="checkbox" value="d">D </label></li>
<li><label><input type="checkbox" value="e">E </label></li>
<li><label><input type="checkbox" value="f">F </label></li>
</ul>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment