MikeW
MikeW

Reputation: 4809

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!

Upvotes: 0

Views: 838

Answers (1)

Ingro
Ingro

Reputation: 2841

Well the selected element is bound by:

value: selectedSubWidget

So you should simply initialize selectedSubwidget with your default value.

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

Upvotes: 1

Related Questions