Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable first option in an Ember.js select menu

I'm pretty new to Ember, and I'm loving it so far! However, I feel like I've lost a little bit control over some of my HTML elements, in particular the <select> menu and it's <option>s.

I'd like for the default (selected) <option> to be disabled as well, i.e. have the attribute disabled. I'm used to this approach for setting a "placeholder" on select menus, but I'm up for other suggestions as well.

For example, if I had a select menu for gender, I'd want to end up with this piece of code:

<select>
  <option selected disabled>Please select gender</select>
  <option value="m">Male</select>
  <option value="f">Female</select>
</select>

I have the following JavaScript and Handlebars code:

JavaScript

genders = [
  Ember.Object.create({value: 'm', label: 'Male'}),
  Ember.Object.create({value: 'f', label: 'Female'}),
];

App.GenderSelect = Ember.Select.extend({
  contentBinding: "genders",
  optionValuePath: "content.value",
  optionLabelPath: "content.label"
});

Handlebars

{{view App.GenderSelect prompt="Please select gender"}}

Generated HTML

This gives me almost the code that I want. However, the first <option> is missing the disabled attribute, hence this question.

<select>
  <option value>Please select gender</select>
  <option value="m">Male</select>
  <option value="f">Female</select>
</select>

Also, it doesn't set the selected attribute, but that's not strictly necessary, because it is the first option in the menu.

I appreciate any answers, both direct answers to this question and valid suggestions for using some other approach than disabled.

Thanks in advance!

like image 902
sindrenm Avatar asked Mar 23 '13 00:03

sindrenm


1 Answers

That HTML is hard-coded into the template and there's no brain-dead simple way to do it.

That said, you can subclass Ember.Select with the following

didInsertElement: function () {
    this.$('option:first').attr('disabled', true);
}

You could also use the layout property to insert the placeholder manually above the auto-rendered options:

layout: precompileTemplate("<option selected disabled>Please select gender</option>{{yield}}")

Seeing as that would also require a subclass, I think it wiser to use didInsertElement.

like image 87
Christopher Swasey Avatar answered Nov 13 '22 07:11

Christopher Swasey