简体   繁体   中英

How set selected value in select list with knockout.js?

I have a binding with a foreach and in one of the properties I have a value where I store the age in years. So far so good, but how to make the selectedoptions to actually adding the selected attribute?

<select  data-bind="attr: { selectedOptions: AgeYears }" selectedoptions="4">
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>

I would like to have the end result like this:

<option selected value="4">4</option>

The usual way to do this, is to have both the options, and the selected option as observables on your viewmodel. You seem to hardcode the options, which is fine too.

<select data-bind="value: AgeYears, valueUpdate: 'change, keyup'">
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
</select>

http://jsfiddle.net/xrmat/

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