I need to make checkAll functionality by clicking on a button. Everything works fine, if the individual box is not clicked to check/uncheck. As soon as you click on one, it will not sync with the button click.
<div x-data="handler()">
<button @click="selecAll = !selectAll">Select All</button>
<div>
<input type="checkbox" x-bind:checked="selectAll">
<input type="checkbox" x-bind:checked="selectAll">
<input type="checkbox" x-bind:checked="selectAll">
</div>
</div>
function handler() {
return {
selectAll: false,
};
}
Just click on any checkbox and it will not work with the button click anymore.
the x-bind directives sets the value of the html attribute.
in your snippet it's toggling the checked attribute correctly if you inspect the dom.
checkboxes ignore the attribute as soon as you start interacting with them, it's the standard behaviour in html: for example, if you have a static page with a checkbox marked as checked and you load that page, you'll see both the tick and the html attribute in the browser console and If you click on that checkbox, it will lose the tick but the attribute will still be there.
At the moment, the only way to do that is using a list of x-models like https://codepen.io/SimoTod/pen/MWaxOrW
It would be probably a good idea to support a prop modifier like vue does (in the future): https://vuejs.org/v2/api/#v-bind. (Setting the property would toggle the checkbox at any time)
Thank you @SimoTod for clearing the doubts. I missed it completely, now I remember when using jQuery i had to use prop for these type of stuffs.
We need prop modifier in Alpine.
@SimoTod
One thing I forgot, When clicking on button, how to get the value of all those checkboxes ?
```html
```
x-model only let me choose true or false base on current states.
Basically I am trying to get the values of selected boxes to perform delete or update of records in database. I can get individual value of checkbox either by$eventor$ref` magic property without any problem.
I've updated the codepen. For checkboxes, your x-model can also be a list of values matching all of them with each checkbox referring the same model. How you build that list depends on your implementation.
Good solution,
I ended up using native JavaScript way. I used querySelector to get those checkboxes and then looping them to get the value if it is checked.
If they are unchecked, removing the value.
@sanjayojha Are you okay with closing this issue if you don't have any other questions? Thanks
Yes sure. I am doing it for you, and sorry for not doing earlier.