Michael Gadd
Michael Gadd

Reputation: 21

Ember action preventing checkbox value from setting

In my ember application I would like to render a set of checkboxes dynamically via a loop and disable any unselected checkboxes if 2 of the checkboxes have been checked.

I am having problems with setting a value to 'true' when a checkbox is selected that has a change action. For the following example checkbox.value does not get set when the checkbox is selected.

{{ input type="checkbox" disabled=checkbox.disabled checked=checkbox.value change=(action "disableCheckboxes" val)}} {{checkbox.label}}

However when I remove the action it does get set:

{{ input type="checkbox" disabled=checkbox.disabled checked=checkbox.value}} {{checkbox.label}}

Full example on JSFiddle

How can I set the value while still running the action? Or is the a better way to disable the unchecked checkbox when 2 have already been selected?

Upvotes: 0

Views: 1062

Answers (1)

Lux
Lux

Reputation: 18240

Well, first you can use an action. Checkout this ember-twiddle.


But I would recommend to directly bind your value to your target object. See here.

The idea is basically to wrap your array and calculate the isDisabled in the wrapping:

boxes:[{id:1,value:true},{id:2},{id:3}],
boxArr: Ember.computed('[email protected]', {
  get() {
    let disableOthers = Ember.get(this, 'boxes').filterBy('value', true).get('length') >= 2;
    return Ember.get(this, 'boxes').map(origin => {
      return {
        origin,
        disabled: disableOthers && !origin.value,
      };
    });
  }
}),

Then you can just use it in your template:

{{#each boxArr as |box|}}
  {{input type="checkbox" disabled=box.disabled checked=box.origin.value}} {{box.origin.id}}
{{/each}}

A third way to archive is with a helper. You can just have a computed property saying if all checkboxes with value=false should be disabled, and then use an and and not helper to set disabled=(and disableFalseCheckboxes (not box.value). Checkout ember-truth-helpers for that.

Upvotes: 2

Related Questions