1

I have lots of models and show them in tables. When user needs to do something with several models, we need to give him ability to choose rows.

How can I implement it with checkboxes? Of course I don't want to create special field on my models for every table.

This is simple example. https://ember-twiddle.com/0b8f429f6ad3e0572438

My tries were:

{{input type='checkbox' checked=model.someNotExistedField}} 

But in this case input just doesnt work.

And:

<input type="checkbox" {{action marked model}}  checked={{in-arr record selectedItems}} />

In second example I've tried to keep selected ids in an array on context. But id doesnt work too.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Costa
  • 634
  • 3
  • 18

3 Answers3

3

There are a few steps to solving this problem, which you have not shown in your code examples.

  1. you dont need to worry about binding a checked value on the checkbox.. it can manage its own internal state, and you can take advantage of it when selecting an item... a native <input> should be fine

    <input type="checkbox">

  2. You will need an action (preferably a closure action) that handles what to do when a record is selected

    onchange={{action (action "valueHasChanged" item) value="target.checked"}}

  3. You will need an array to store the "selected items"

    this.selectedItems = [];

I put together a twiddle as one example of how these pieces fit together.

(This answer should be valid with ember version 1.13.0 and up)

Grapho
  • 1,654
  • 15
  • 33
0

I'am guessing your model is an array of rows. So try adding a chked (boolean) property to the model structure so you now have one for each row and bind it to the respective checkbox.

Rakesh G R
  • 804
  • 12
  • 24
  • The same model could be checked on one table and be not checked on other table. I need some way that with no dependencies on what model we use. – Costa Feb 16 '16 at 12:25
  • http://stackoverflow.com/questions/19766044/best-way-to-get-all-selected-checkboxes-values-in-jquery/19766067#19766067 @user1871941 – Rakesh G R Feb 17 '16 at 09:15
0

I finished with such technic:

  1. components/action-based-checkbox.hbs

{{#if checked}}
    <input type="checkbox" {{action changed}}  checked="checked" />
{{else}}
    <input type="checkbox" {{action changed}} />
{{/if}}
  1. In context we have array with selected items, for instance "selectedItems"

  2. In context we have an action, that manages array

      //2 and 3 steps example
    
      actions:{
        marked(id){
          this.selectedItems.push(id);
          var uniq = this.selectedItems.uniq();
    
          this.set('selectedItems', uniq);
    
        },
      selectedItems:[],
    

4.next I put the component to my cell

{{inputs/action-based-checkbox changed=(action marked record.id) checked=(in-arr record.id selectedItems)}}

in-arr my "in_array?" helper, ember 2.3

Costa
  • 634
  • 3
  • 18