Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Predefine the selected value in dropdown list

Tags:

knockout.js

I have the following issue:

I have an observable array of objects in the format { isSelected: false, Message: "Test1" }, { isSelected: true, Message: "Test2"}. I am generating a select list in the view from this observable array. I want the value with the property isSelected = true to be preselected ( that will be: Message: "Test2" in this example). Here is my code:

Knockout:

function ViewModel()
{

    this.DummyOptions = ko.observableArray([{ isSelected: false, Message: "Test1" }, { isSelected: true, Message: "Test2"}]);
    this.selectedValue = ko.observable();
}

ko.applyBindings(new ViewModel());

Html:

<div>
Dummy
<select id="dummy" data-bind="options: DummyOptions, optionsText: 'Message'"></select>
</div>

Fiddle: http://jsfiddle.net/PsyComa/RfWVP/52/

I believe this will be simple but I am very new to knockout and I was not able to make it work as expected. Any help with working code will be greatly appreciated. Thank You.

like image 729
Mdb Avatar asked Apr 26 '12 15:04

Mdb


1 Answers

You're right, this is indeed very simple with knockout.js.

An observable can be bound to the currently selected option using the "value" binding:

<select data-bind="options: DummyOptions,
                   optionsText: 'Message',
                   value: selectedValue"></select>

Now, just use the object with "isSelected == true" as the initial value of this observable:

function ViewModel() {
    this.DummyOptions = ko.observableArray([...]);

    // Filter the array to find the first element with isSelected == true
    var selectedOption = ko.utils.arrayFirst(this.DummyOptions(), function(item) {
        return item.isSelected;
    });

    // Use this option as the initial value
    this.selectedValue = ko.observable( selectedOption );
}

http://jsfiddle.net/RfWVP/54/

like image 86
Niko Avatar answered Oct 03 '22 01:10

Niko