简体   繁体   中英

Knockoutjs - how to preselect 1st option in select dropdown

Say I have a select box eg

<div data-bind='visible: someProp'>   
   <select class="selectSubWidgets" data-bind='options: subWidgets,optionsText:          "Name", optionsValue : "Name", optionsCaption: "[Select a Widget]",attr: {name: "Widgets[" + $parent.widgets.indexOf($data) + "].Name"}, value: selectedSubWidget'></select>
</div>

If count of items in this select is only 1 - currently I hide this drop down (working) but I also want to ensure that the single item is selected (while hidden) (so the 1st value is bound in form post). Is there a way to express this binding?

Thanks!

Well the selected element is bound by:

value: selectedSubWidget

So you should simply initialize selectedSubwidget with your default value.

this.selectedSubWidget = ko.observable("defaultValue");

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