JackH
JackH

Reputation: 4735

Ember loop through an array of checkboxes and get checked items?

I have an Ember.js application (using the Ember CLI). I have a component called sideMenu with the files sideMenu.js and sideMenu.hbs. Within the .js file, I have an array of vehicle names like this:

export default Ember.Component.extend({
    vehicles: ['Audi', 'Chrysler', 'Harley Davidson'],
    vehicleCheckboxes: { 'Audi': true, 'Chrysler': true, 'Harley Davidson': true }
});

In my template for this component, I am looping through these vehicles and creating a checkbox for each item like this:

{{#each vehicles as |vehicle|}}
    {{input type='checkbox' checked='true'}} {{vehicle}}
{{/each}}

This gives me what I want - a few checkboxes with the vehicle names next to it. I want to be able to know what the user unchecked / checked in this list. I tried to do this by creating some Ember properties dynamically and in the template:

{{input type='checkbox' checked="{{vehicleCheckboxes}}.{{vehicle}}"}}

This didn't seem to work though. How can I accomplish this? There doesn't seem to be any indication on the Ember documentation that it is possible from within the framework in any way.

Upvotes: 1

Views: 698

Answers (1)

Bek
Bek

Reputation: 3207

checked expects boolean value (true/false) you can either use this addon like :

{{multiselect-checkboxes options=vehicles selection=selectedVehicles}}

or you can have your loop like this:

{{#each vehicles as |vehicle|}}
    {{input type='checkbox' checked=(get vehicleCheckboxes vehicle)}} {{vehicle}}
{{/each}}

and you need your vehicleCheckboxes converted to Ember.Object I think if it does not work as it is

vehicleCheckboxes: Ember.Object.create({ 'Audi': true, 'Chrysler': true, 'Harley Davidson': true })

Upvotes: 2

Related Questions