0

I am implementing a dropdown using Ember, but I cannot set the selected property of an option element using a handlebars expression.

Here is an ember-twiddle example that shows the issue. Notice how in the DOM of the twiddle, the selected attribute does not appear for the top example.

<select
    aria-disabled="{{disabled}}"
    aria-multiselectable="{{multiselect}}"
    disabled={{cannotOpen}}
    onchange={{action 'itemClicked' value='target.value'}}
>
    <option selected disabled value="">{{placeholder}}</option>

    {{#each items as |item|}}
        <option 
            value={{item.value}}
            selected={{if (is-item-selected item.state) "selected"}}
            disabled={{item.disabled}}
        >
            {{item.name}}
        </option>
    {{/each}}
</select>

"is-item-selected" is a custom helper that returns true if "item.state === 2", which is does when the item is selected in the dropdown.

No matter what I try in the handlebars, the selected attribute will not display (e.g. selected={{if true "selected"}} does not work either). However, changing selected to data-selected works exactly as intended.

Is anyone aware of this issue? Or am I misunderstanding how the selected attribute is supposed to work?

Kameron Kincade
  • 514
  • 1
  • 7
  • 18
  • You may want to show the is-item-selected helper. Does it do any kind of async operation? That would return void rather than the selected state boolean. For me, your Twiddle looks like it was working as expected. The selected doesn't re-order the options, but just marks the options where it has a value as selected (which should show in the select prior to opening it). – LocalPCGuy May 30 '18 at 17:48

1 Answers1

2

So this is actually a "feature" of the dom/html. Classes and data attributes are attributes, while the selected is a property.

There's a great write-up here (about this same issue!)

And if you want to go direct (I stole this from the other answer): .prop() vs .attr()