1

I have a table with checkboxes as the first column. I want to have a select all checkbox in the header. I'm not sure how to approach this problem.

<template>
  <table class="table table-hover">
      <thead>
        <tr>
          <th><input type="checkbox" /></th>
          <th>ID</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td><input type="checkbox" checked.bind="selected" model.bind="site" /></td>
          <td>${site.id}</td>
        </tr> 
      </tbody>
    </table>  
</template>

1 Answer 1

1

So, the very best way to solve this problem has three parts. We need to bind the checked attribute and the indeterminate attribute, and we need to handle the change event.

First, we want the checkbox to be checked whenever the selected array has all the items in the items array. So:

<input type="checkbox" checked.bind="selected.length === items.length" />

This checks the checkbox whenever all items are selected, but checking the checkbox has no effect on the selected array yet.

Next, we want the checkbox to be indeterminate whenever selected array has some but not all items in the items array. So:

<input type="checkbox 
  checked.bind="selected.length === items.length"
  indeterminate.bind="selected.length > 0 && selected.length < items.length" />

Now, the checkbox completely reflects the state of the selected array, but still has no effect on the selected array.

Finally, we can listen to the change event on the checkbox to update the selected array whenever the checkbox is checked or unchecked. I use an inline handler below, and in this handler $event.target is the checkbox itself.

<input type="checkbox"
  checked.bind="selected.length === items.length"
  indeterminate.bind="selected.length > 0 && selected.length < items.length"
  change.delegate="$event.target.checked ? selected = items.slice() : selected = []" />

At this point, the checkbox is working perfectly. Checked is normally a two-way binding, but in our example above it is only operating one-way. We can make this small optimization:

<input type="checkbox"
  checked.one-way="selected.length === items.length"
  indeterminate.one-way="selected.length > 0 && selected.length < items.length"
  change.delegate="$event.target.checked ? selected = items.slice() : selected = []" />

See this gist.run for a working example: https://gist.run/?id=61cc823708ff7f6ba195de9ff0353049

Note that I typically find it useful to create a custom element that encapsulates this behavior.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.