I'm generating a datalist
options based on a ko observable.
function Company(company) {
this.id = company.Id;
this.name = company.Name;
this.state = company.State.name;
}
var self = this;
self.companies = ko.observable();
$.get('...', {}, function(result) {
ko.utils.arrayForEach(result, function(company) {
self.companies.push(new Company(ko.toJS(company)));
});
});
HTML:
<input type="text" data-bind="value: selectedCompany" list="companiesList" />
<datalist id="companiesList" data-bind="foreach: companies">
<option data-bind="value: name, text: state"></option>
</datalist>
Ok, here's the deal: in the Company
function, I store the Id from that company. What I want to do? Something that able me to link the Id value to selectedCompany variable instead the name? I want to display the name property, but I need to store the Id.
Is there a way to do this? Thank you all!
would you like something like this?
HTML
JAVASCRIPT
Knockout has already some options to create this selects.. see it in documentation http://knockoutjs.com/documentation/options-binding.html
http://knockoutjs.com/documentation/options-binding.html
Since there is currently no Knockout binding for HTML5
<datalist>
, I made one.I tried to borrow as much as I could from the
select
binding, so there is support foroptions
,optionsText
andoptionsValue
. You can specify a target observable viavalue
.I hope I got most of this right. Corrections and improvement suggestions are welcome.
You would use it like this:
Notes.
<datalist>
in the HTML. The custom binding does that for you.list=""
attribute of the<input>
element. I found no way of dynamically setting that in JavaScript so far.value
is optional, but if you supply it, it must be an observable.value
binding outside ofdatalist
. It will contain whatever text the<input>
displays (no surprises there). However, writing to the built-in value also updates thedatalist
value, and the other way around.datalist
value has precedence and will overwrite the built-in value upon view model init. After that they stay in sync.options
should be an array (plain old or observable) of objects — companies in this case).optionsText
andoptionsValue
are strings that should map to properties on your options.optionsValue
— in that case the entire object (a single company) would be stored invalue
. I would prefer that over storing only the ID.change
event. That means your view model won't update until you leave the input field.Below is a demo, copied from the original fiddle.