Here is the code snippet I am currently working with:
var model = function() {
this.nameSomething = ko.observable('');
this.nameId = ko.observable(0);
};
var vm = (function() {
var myList = [{ id: 1, type: 'foo1'}, { id: 2, type: 'foo2' }, { id: 3, type: 'foo3' }],
selectedModel = ko.observable(model);
return {
myList: myList,
selectedModel: selectedModel
};
}());
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div data-bind="with: selectedModel">
<select data-bind="options: $root.myList,
optionsText: 'type',
optionsValue: 'type',
value: nameSomething"></select><br />
Display this: <span data-bind="text: nameSomething"><br />
Store this: <span data-bind="text: nameId"><br /> <!-- not displaying anything -->
<pre data-bind="text: ko.toJSON($root.selectedModel, null, 2)"></pre>
</div>
Can I save the value of optionsValue
in nameId
and the text from optionsText
in nameSomething
when the option is loaded/changed?
I need to show the selected text in the UI while storing the corresponding value in the database.
Any assistance on this issue would be greatly appreciated. I am also open to any tips for beginners using Knockout JS.
UPDATE
Added a working example