Stop checkbox from being check in alpineJS?

Viewed 1574

i started using alpine JS in my project and encountered this situation, i dont really know the best way to approach this. I have a input checkboxes and i need to restrict the user to only select 12 of them. I could probably do this in plain javascript or jquery, but since ive decided to use alpine JS might use it all the way. so heres my question

i have a input type checkbox like this:

<input type="checkbox" @click="toggle = !toggle, count = count + 1">

and have a parent div that holds the state:

<div x-data="{ count: 0 }">

as a parent of the input, so if i have for example 24 of the checkboxes.. how do i make it so the user cant click on more than 12 of the checkboxes?

1 Answers

You can bind to disabled and check count >= 12.

<div x-data="{ count: 0 }">
  <input
    type="checkbox"
    :disabled="count >= 12"
    @click="toggle = !toggle, count = count + 1"
  >
</div>
Related