简体   繁体   中英

Selected Attribute on Select Option Not Working (Ember.js + Handlebars)

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 (eg 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?

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM