Svelte:Checkboxes and radio buttons

Checkboxes and radio inputs (input elements with type="checkbox" or type="radio") allow those 3 bindings:

  • bind:checked
  • bind:group
  • bind:indeterminate

bind:checked allows us to bind a value to the checked state of the element:

<script>
let isChecked
</script>

<input type=checkbox bind:checked={isChecked}>

bind:group is handy with checkboxes and radio inputs, because those are very often used in groups. Using bind:group you can associate a JavaScript array to a list of checkboxes, and have it populated based on the choices made by the user.

Here’s an example. The goodDogs array populates based on the checkboxes I tick:

<script>
let goodDogs = []
let dogs = ['Roger', 'Syd']
</script>

<h2>
  Who's a good dog?
</h2>

<ul>
  {#each dogs as dog}
    <li>{dog} <input type=checkbox bind:group={goodDogs} value={dog}></li>
  {/each}
</ul>

<h2>
  Good dogs according to me:
</h2>

<ul>
  {#each goodDogs as dog}
    <li>{dog}</li>
  {/each}
</ul>

See the example on https://svelte.dev/repl/059c1b5edffc4b058ad36301dd7a1a58

bind:indeterminate allows us to bind to the indeterminate state of an element

Leave a comment

Your email address will not be published. Required fields are marked *