I'm using the KnockoutJS Autocomplete code found here:
How to create an auto-complete combobox?
Generally it's working just fine. I'm using a JQuery Ajax call to get the data for the Autocomplete. When I type into the input field, then select a value from the list, the corresponding value is set in the Knockout ViewModel. However, I can't get it to set the selected text value from the autocomplete.
(This is to be able to look up SIC numbers, given a partial description)
I have defined:
function Sic(SICCode, SICDescription) {
var self = this;
self.SICCode = ko.observable(SICCode);
self.SICDescription = ko.observable(SICDescription);
}
My ViewModel has:
self.SICCode = ko.observable("");
self.SICDescription = ko.observable("");
self.SicCodes = ko.observableArray();
and the lookup function is:
self.getSicCode = function (searchTerm, sourceArray) {
$.getJSON(_serviceURL + "/GetSicFromDescription/" + searchTerm, function (data) {
if (data.length > 0) {
var result = [];
$.map(data, function (item) {
result.push(new Sic(item.SicCode, item.Description));
});
sourceArray(result);
}
});
}
In the input tag (it's actually a .NET page (and actually a DotNetNuke custom module, but that doesn't matter for this) ) I have:
<div>SIC:<br />
<input type="text" maxlength="30"
data-bind="value: SICDescription,
jqAuto: {minLength: 3, autoFocus: true}, jqAutoQuery:getSicCode,
jqAutoSource: SicCodes, jqAutoSourceLabel: SICDescription,
jqAutoValue: SICCode, jqAutoSourceInputValue: 'SICDescription',
jqAutoSourceValue: 'SICCode'" />
<span data-bind="text: SICCode"></span>
</div>
(I've tried with and without the value: binding) Typing into the input box will correctly do the lookup and present the list of matching items. I can then select one and see the corresponding number in the span.
However, when I then click a button that then sends the ViewModel data to the server, the self.SICDescription() is empty... self.SICCode() contains the correct value.
So, how do I get the selected description populated into the ViewModel? I would have assumed using the value binding for the input field should have done the trick. But no go.
Is there anyway to do what I need, or am I going to have to do some work around (looping through the array of returned values and pluck out the right description)?
Thanks.