I would like to know how to get the value of the TEXT selected from the dropdown menu, just remember that my drop down menu has the fixed data and are not populated by a "ko.observableArray ()". Any ideas?
When I select an option want to have: Value and Text selection.
<p>
Select a car:
<select data-bind="value: selectedValue, optionsText:???">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</p>
<span data-bind="text: selectedValue"></span>
<br/>
<span data-bind="text: selectedText"></span>
My ko ViewModel:
var viewModel = {
selectedValue : ko.observable(),
selectedText : ko.observable()
};
ko.applyBindings(viewModel);
See this Fiddle: JSFiddle
I dont know if there is a possible solution with Knockout.js. I let you two possible solutions:
Solution 1
You can use a bit of native Javascript to achieve your goal:
As you see, you can take the "value" and use it to return the DOM element that meets your requirements. Of course you can replace
select
with an id, if you need it.Check this fiddle to see it working.
Solution 2
The Knockout way of doing this is having an array with all elements to be populated:
After that, it depends on what you need when you say "
value
", remember that you are binding an object, not a key/value list:HTML:
And your JS:
This way you will have separately your "value" and your "text" (better called
id
andname
properties) into two computed observables.See the fiddle working.