Tom Nolan
Tom Nolan

Reputation: 1957

How to get a value from a self populated dropdown using knockout?

I have a select menu that is populated using the foreach data bind:

self.priorityOptions = ko.observableArray(["Low", "Normal", "High"]);

<select data-bind="options: priorityOptions"></select>

This works perfectly fine, but I'm using this dropdown to create objects in another array, but I'm trying to use that dropdown to specify one of the object's parameters:

self.createTicket = function() {
    self.tickets.push({priority: *********});
}

If I put an actual string where the asterisks are, the object is created correctly, but that means I need to manually type each one. Is there a binding I can use on the select element in order to pull which choice is currently selected and insert that into the array push?

I've seen selectedOptions but I could not get that to successfully work, any ideas?

Upvotes: 2

Views: 104

Answers (1)

Phil-R
Phil-R

Reputation: 2253

Your select is not "multiple", so I guess you have a button and you want to create your ticket with the selected priority at that moment. Bind your selected value to your view model, then use the value in your createTicket function.

self.priorityOptions = ko.observableArray(["Low", "Normal", "High"]);
self.selectedPriority = ko.observable();

<select data-bind="options: priorityOptions , value: selectedPriority"></select>

self.createTicket = function() {
    self.tickets.push({priority: self.selectedPriority()});
}

Upvotes: 1

Related Questions