Skip to content

Instantly share code, notes, and snippets.

@rg3915
Last active March 15, 2023 05:23
Show Gist options
  • Save rg3915/54c7af62e996c54c375c9dff58a813c4 to your computer and use it in GitHub Desktop.
Save rg3915/54c7af62e996c54c375c9dff58a813c4 to your computer and use it in GitHub Desktop.
Select all checkbox with AlpineJS - select all alpinejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
<link rel="shortcut icon" href="http://html5-training-in-hyderabad.blogspot.com.br/favicon.ico">
<link rel="shortcut icon" href="https://www.djangoproject.com/favicon.ico">
<link rel="shortcut icon" href="https://alpinejs.dev/favicon.png">
<title>AlpineJS</title>
<!-- Bulma -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css">
<!-- Font-awesome -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- Alpine.js -->
<script src="//unpkg.com/alpinejs" defer></script>
</head>
<body>
<div
class="container mt-5"
x-data="getTodos"
>
<p>
<span>Itens:</span>
<span x-text="selectedItems"></span>
</p>
<p>
<span>Linhas selecionadas:</span>
<span x-text="selectedRows"></span>
</p>
<table class="table">
<tbody>
<tr>
<td>
<input
type="checkbox"
:checked="selectAll"
@click="toggleAllCheckboxes"
>
</td>
<td>Selecionar todos</td>
</tr>
<template
x-for="(item, index) in items"
:key="item.id"
>
<tr>
<td>
<input
:id="'item-'+index"
type="checkbox"
:value="item.id"
x-model="selectedItems"
x-ref="row[index]"
>
</td>
<td x-text="item.task"></td>
</tr>
</template>
</tbody>
</table>
</div>
<script src="./main.js"></script>
</body>
</html>
const getTodos = () => ({
items: [],
selectedItems: [],
selectAll: false,
selectedRows: [],
init() {
this.getData()
},
getData() {
// https://jsonplaceholder.typicode.com/todos
fetch('http://localhost:3000/todos/')
.then(response => response.json())
.then(data => {
this.items = data
})
},
toggleAllCheckboxes() {
this.selectAll = !this.selectAll
this.selectedItems = this.selectAll ? this.items.map(item => item.id) : []
// Opção usando Vanilla Javascript
// Seleciona todos os checkboxs que começam com "item".
let checkboxes = Array.from(document.querySelectorAll("[id^='item']"))
checkboxes.forEach(item => {
console.log(item.value)
})
// Está incompleto porque não marca os checkbox com JS puro.
// Obtem um array de valores do checkbox.
const selectedValues = checkboxes.map(item => item.value)
console.log(selectedValues)
this.selectedRows = this.selectAll ? selectedValues : []
},
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment