简体   繁体   中英

knockoutjs set select default selected value

I'm using knockout.js and trying to set the default value (not use optionCaption) of my select binding as well as capture the value when anyone changes it.

<div class="customization-container" data-bind="foreach: customization">
    <div class="clear-both option">
        <label data-bind="text: Name"></label>
        <select data-bind="options: AvailableValues, value: Value></select>
    </div>
</div>

What I have in AvailableValues is an array like [1, 2, 3, 4] or ["Row", "Run", "Paddle", "Ski"] and I want to be able to pick which one of the values is the default.

I can't find anything in the knockout.js documentation or online yet. I don't want to set a caption, I want the default to be a literal value from the array.

Thanks!

You're doing it just the way you should (apart from a missing double quote to close your data-bind attribute). See this example:

 var vm = { AvailableValues: [1,2,3], Value: ko.observable(2) }; ko.applyBindings(vm); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> <select data-bind="options: AvailableValues, value: Value"></select> 

Which would work equally fine for a list of strings:

 var vm = { AvailableValues: ["Row", "Run", "Paddle", "Ski"], Value: ko.observable("Paddle") }; ko.applyBindings(vm); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> <select data-bind="options: AvailableValues, value: Value"></select> 

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