sindrenm
sindrenm

Reputation: 3492

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!

Upvotes: 5

Views: 2455

Answers (2)

Scott Stafford
Scott Stafford

Reputation: 44798

This answer shamelessly leverages @ChristopherSwasey's answer, but will affect all Ember.Selects globally that use the prompt attribute.

Ember.Application.initializer({
    name: 'ember-select-with-nullprompt',

    initialize: function(container, application) {
        Ember.Select.reopen({
            didInsertElement: function () {
                if (this.prompt)
                    this.$('option:first').attr('disabled', true);
            }
        });
    }
});

Upvotes: 0

Christopher Swasey
Christopher Swasey

Reputation: 10552

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.

Upvotes: 6

Related Questions