[英]Indeterminate Checkboxes with Alpine.js
我正在嘗試使用 Alpine.js 實現不確定的復選框
您可以 select 所有復選框,但是當您嘗試取消選中某些復選框時,所有復選框都未選中。
看看: https://codepen.io/nuno360/pen/gOwXpXP
<table x-data="{ allChecked: [] }"
x-init="
$watch('allChecked', value => {
if (value.length === 0) {
$refs.all.indeterminate = false;
$refs.all.checked = false
} else if (value.length == all.length) {
$refs.all.indeterminate = false;
$refs.all.checked = true
} else {
$refs.all.indeterminate = true
}
})
" class="bg-white min-w-full divide-y divide-gray-200">
<thead>
<tr>
<th scope="col" class="h-14 leading-none" width="60"><input id="all" x-ref="all" @change="allChecked = $event.target.checked ? all : []; console.log(allChecked)" type="checkbox" class="form-checkbox border-gray-300 h-5 w-5 cursor-pointer rounded"></th>
<th scope="col" class="h-14 text-left text-xs text-gray-800 uppercase">Name</th>
<th scope="col" class="h-14 relative px-6"><span class="sr-only">Editar</span></th>
</tr>
</thead>
<tbody class="divide-y divide-gray-200">
<tr class="hover:bg-gray-100">
<td class="h-14 leading-none text-center" width="60">
<input name="delete[]" x-model="allChecked" value="1" type="checkbox" class="form-checkbox border-gray-300 h-5 w-5 cursor-pointer rounded">
</td>
<td class="py-4 whitespace-nowrap text-sm text-gray-500">
Regional Paradigm Technician
</td>
<td class="px-5 py-4 whitespace-nowrap text-right text-sm font-medium">
<a href="#" class="text-blue-600 hover:text-blue-900">Editar</a>
</td>
</tr>
<tr class="hover:bg-gray-100">
<td class="h-14 leading-none text-center" width="60">
<input name="delete[]" x-model="allChecked" value="2" type="checkbox" class="form-checkbox border-gray-300 h-5 w-5 cursor-pointer rounded">
</td>
<td class="py-4 whitespace-nowrap text-sm text-gray-500">
Inter Paradigm
</td>
<td class="px-5 py-4 whitespace-nowrap text-right text-sm font-medium">
<a href="#" class="text-blue-600 hover:text-blue-900">Editar</a>
</td>
</tr>
</tbody>
</table>
感謝幫助。
無法取消選擇單個選項的原因是因為下面一行中的all
內容都給出了 ref,它是watch
function 的 dom 元素。
<input id="all" x-ref="all" @change="allChecked = $event.target.checked ? all : []; console.log(allChecked)" type="checkbox" class="...">
如果選中all
復選框,我們需要將allChecked
數組設置為['1','2']
所以要解決這個問題,
<input id="all" x-ref="all" @change="allChecked = $event.target.checked ? ['1','2'] : []; console.log(allChecked)" type="checkbox" class="...">
更新
要自動傳遞值,我們可以使用 function 將復選框的所有值收集到數組中,如下所示。
<table x-data="{ allChecked: [], getValues(){
var array = []
var checkboxes = document.querySelectorAll('input[x-model=allChecked]')
for (var i = 0; i < checkboxes.length; i++) {
array.push(checkboxes[i].value)
}
return array;
} }" x-init="..." >
並使用getValues
function 而不是如下硬編碼。
<input id="all" x-ref="all" @change="allChecked = $event.target.checked ? getValues() : []; console.log(allChecked)" type="checkbox" class="...">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.