Learn Quickly: Working With a List of Checkboxes
A common element in any UI is a list of checkboxes to toggle different options, filters, etc.
Not long ago I worked on a large grid of data where checkboxes were used to toggle which columns would be displayed in the grid. These selections were also saved in the database, so a user could save their selections in a sort of template.
Working with checkboxes should be simple, but because there can be many changes that are driven by the checkbox data, the mental model can sometimes grow a bit complex, making the simple seem a bit more overwhelming (at least in my experience).
Sometimes simple things, when attached to more complex workflows, can seem much more difficult than they really are.
Handling an Array of Selected Checkboxes
In my own code, I’ve settled on a couple ways to work with an array of selected checkbox values.
- Use a custom watcher function
- Use a
@change
callback.
I tend towards using a callback (option 2) unless I need access to the previous value of the array for some reason.
I like seeing the @change
in the template, as that’s where I tend to look when I’m curious about what’s going to happen when an input is changed.
But that’s just me. It’s entirely up to you.
Watch Out!
A mistake I’ve made a couple times is to forget to set the :value
attribute on the checkbox input.
If this isn’t set to something unique, like :value="user.id"
or to the object itself :value="user"
then selecting and deselecting boxes will behave very strangely as nothing will actually be sent to the associated v-model. Test it out and see.
Here’s the general flow:
- data() has my starting array that populates my checkbox values and labels.
- data() also initializes my
selectedItems
array that will either be watched or used in the method chosen as the callback on the change event.
Syncing Selections with Async Data
In my case, I needed to make sure the checkbox selections were set properly after loading a user-defined template.
A user would first load the grid with default selections made. Then when a user chose to load a saved filter template, the column selections / checkbox states needed to reflect that new setting.
Fortunately, Vue makes this (and many other things) very easy.
The Demo
Found this helpful?
If this short post has helped you in any way, please remember to give this a recommendation below and post a brief comment to support me.
Comments, questions and constructive feedback are always welcome.
My name is Patrick O’Dacre, and I’m chief builder at BuildtoLearn.io — a place where growing developers can get more comfortable with full stack development by helping aspiring entrepreneurs build application prototypes.
If you’re interested in full stack JavaScript development and getting more experience with taking a full application from Zero to Production, visit BuildtoLearn.io and sign up for updates.