Bronzato
Bronzato

Reputation: 9332

Preselect an item in my dropdown with knockout

I have the following dropdown:

<div>  
    Dummy
    <select data-bind="options: categories, optionsText: 'description', value: 2"></select>
</div>

With the javascript below:

function ViewModel()
{

    this.categories = ko.observableArray([
            new Category(1, "Non classé"),
            new Category(2, "Non nucléaire"),
            new Category(3, "Classe II irradié"),
            new Category(4, "Classe III")
    ]);

    // Constructor for an object with two properties
    function Category(id, description) {
        this.id = id;
        this.description = description;
    };
}

ko.applyBindings(new ViewModel());

I would like to pre-select the element with the id of 2 in the dropdown.

Any idea?

Thanks.

jsFiddle: http://jsfiddle.net/RfWVP/276/

Upvotes: 3

Views: 4127

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126042

Two ways I can think of to do this. Either way you'll have to add a selectedCategory observable property to store track the currently selected option.

  1. Use the optionsValue binding and specify 'id' as the property you'd like to use as the value of each option:

    <select data-bind="options: categories, 
                       optionsText: 'description', 
                       value: selectedCategory, 
                       optionsValue: 'id'">                 
    </select>
    

    Then set selectedCategory equal to "2":

    this.selectedCategory = ko.observable(2);
    

    Example: http://jsfiddle.net/RfWVP/281/

  2. Create the category with id "2" before creating your observable array of categories and set the selectedCategory equal to that category:

    var selected = new Category(2, "Non nucléaire");
    
    this.categories = ko.observableArray([
        new Category(1, "Non classé"),
        selected,
        new Category(3, "Classe II irradié"),
        new Category(4, "Classe III")
    ]);
    
    this.selectedCategory = ko.observable(selected);
    

    Example: http://jsfiddle.net/RfWVP/280/

Which one you use depends on what information you need about the selected category.

Upvotes: 7

Related Questions