Ronni Egeriis Persson
Ronni Egeriis Persson

Reputation: 2289

Best way to assign value from radio button selection

I have created this little jsbin, with the framework for my use case: http://emberjs.jsbin.com/kufijixicu/1/edit?html,js,output

What I have tried to achieve in various ways, is to be able to assign the color value based on the selection in the list of radio buttons. I believe there to be a simple solution to this.

The solution must also provide a way where a potential existing value is already selected in the list. So if color is already selected, the selected one should be checked in the list.


Current solution

My current solution may be irrelevant, but I'll post it here for context.

As mentioned, I've tried various solutions. The one I have in my application at this moment works as described, it's buggy and messy which is why I'm looking for a better solution:

The ColorController has an action, which is attached to what would be the <li> in above jsbin:

selectColor: function(color) {
  this.send('setColor', color);
  this.forEach(function(item) {
    item.set('isChecked', item.get('model') == color);
  });
}

The IndexController has the setColor action:

setColor: function(color) {
  this.set('color', color);
}

And the initial selection is set through this observer on the ColorController:

colorsChanged: function() {
  if (this.filterBy('isChecked', true).get('length') == 0) {
    var selectedColorId = this.parentController.get('model.color_id')+'',
        selectedColor = this.filterBy('id', selectedColorId);

    if (selectedColor.get('length') == 0) return;
    selectedColor.objectAt(0).set('isChecked', true);
  }
}.observes('this.[]')

This seems way too messy, but it also doesn't work 100%. For instance, a click on the radio button itself will actually un-check the radio button again.

Upvotes: 0

Views: 67

Answers (1)

Sam Selikoff
Sam Selikoff

Reputation: 12704

In Ember, things like radio buttons and checkboxes are best wrapped up in components. Unfortunately, a few edge cases have prevented Ember from shipping a radio button component as part of core.

The first thing I'd do is see if someone else has already implemented this. Are you using Ember CLI? If not, you should be. Browsing Ember Addons I find two radio button components.

I'd give ember-radio-button a shot.

Upvotes: 1

Related Questions