Josh R
Josh R

Reputation: 2210

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!

Upvotes: 0

Views: 2244

Answers (1)

Jeroen
Jeroen

Reputation: 63709

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>

Upvotes: 1

Related Questions