Anitha Sundaramoorthy
Anitha Sundaramoorthy

Reputation: 203

In ember, how to change values of checkboxes based on another

I have four checkbox and I want to check automatically checkbox with id = 2 if checkbox with id = 4 is checked.

I did the following but did not get the output. Could someone help me with this.

{#each category in checkboxList}}
            {{input id = category.CHECKBOX_ID type="checkbox" checked=category.IS_CHECKED}}
            {{#if category.CHECKBOX_ID == 4 && category.IS_CHECKED == true}}
                {{action 'CheckSize'}}
            {{/if}}

The checkboxList is

[
   {"IS_CHECKED":false,"CHECKBOX_ID":1}, 
   {"IS_CHECKED":false,"CHECKBOX_ID":2},
   {"IS_CHECKED":true,"CHECKBOX_ID":3},
   {"IS_CHECKED":false,"CHECKBOX_ID":4}
]

Upvotes: 0

Views: 66

Answers (1)

NullVoxPopuli
NullVoxPopuli

Reputation: 65143

You'll want to manage the state of the checkboxes separately.

Here is an example I did for another SO question that had a similar problem to solve:

https://ember-twiddle.com/468a737efbbf447966dd83ac734f62ad

The gist of it is we use a single action in response to a click of any checkbox:

  @action
  toggleChecked(id) {
    const newTree = check(this.options, id);

    this.set('options', newTree);
  }

In this example (taken from the ember-twiddle), all of the logic is extracted to a pure-function named check.

Check itself is pretty involved, but because the application logic is different between that example and the problem you've run in to, I'll just show the entry point function:

export function check(tree, id, transform = toggle) {
  if (tree === undefined) return undefined;

  if (Array.isArray(tree)) {
    return tree.map(t => check(t, id, transform));
  } 

  if (tree.id === id || id === 'all') {
    return checkNode(tree, id, transform);
  }

  if (tree.children) {
    return checkChildren(tree, id, transform);
  }

  return tree;
}

This is just an example of how you can immutably modify the representation of all checkboxes by using a pure function. Your logic may vary.

Hope this helps :)

Upvotes: 2

Related Questions