What is the property way to get the value of a select?

What is the ‘Ember’ way to get the value of a Ember Select?

I’ve created a component with the following:

select-state.hbs:

{{view "select" class="form-control" content=items.value optionValuePath="content.city"  optionLabelPath="content.name" prompt="Choose a State"}}

The ‘content.city’ is an object.

select-state.js:

change: function (value) {
        // Get value of select
	debugger;
}

This is how I populated my model (I’m not sure if this is the best way):

var promises = {
   market: Ember.$.getJSON....,
   states: Ember.$.getJSON....,
   properties: Ember.$.getJSON
};

return Ember.RSVP.hashSettled(promises).then(function(hash) {
   return hash;
});

Then to get the selected value of my Ember Select I did the following in my select-state.js component file:

var model = this.get('myModel');
model.market.value.cities.addObject(model.states.value.findBy('name', Ember.$("select[name='test'] option:selected").text()).city);

This is how I pass values to my component:

{{select-state items=states myModel=model}}

I would wrap Ember.Select in your own component, one that embraces data down actions up, and give it a nice API:

{{!-- components/select-input/template.hbs --}}
{{view "select" class=class
  selection=_selection
  content=content
  optionValuePath=optionValuePath
  optionLabelPath=optionLabelPath
  prompt=prompt}}
// components/select-input/component.js
export default Ember.Component.extend({
  _selection: Ember.computed.readOnly('selection'),
  
  emitActions: Ember.observer('_selection', function() {
    this.sendAction('on-select', this.get('_selection');
  })
});

Now you can do something like

{{select-input class='form-control'
  content=items.value
  optionValuePath='content.city'
  optionLabelPath='content.name'
  prompt='Choose a state'
  selection=items.selectedValue
  on-select='change'}}

and in the handler, you’ll have the selected item:

change: function(item) { 
  // do magic with item
}

Code untested, something like this anyway. The selection property is the “data down” part, if you want the <select> to also display the currently selected item (instead of just sending out an action on change).

3 Likes

I haven’t tried it personally, but it looks like someone built an addon to do this. Just trying to save you the troubles :smile:

https://github.com/thefrontside/emberx-select/blob/master/addon/components/x-select.js

2 Likes