0

I have an input field:

<input id="DeviceId" 
       class="form-control deviceCatalog" 
       data-bind="value:DeviceTemp, valueUpdate: ['blur']" 
       required />

Which is bound to this viewModel;

var ViewModel = function () {
    var self = this;
    self.DeviceTemp = ko.observable();
}

And I use jQueryUI autocomplete on it:

function GetNames() {
    var availableTags;
    var jsonData
    $.ajax({
        url: "/DeviceInstance/GetDeviceNames",
        type: "GET",
        dataType: "json",
        error: function (data) {
            alert("wystąpił nieokreślony błąd " + data);
        },
        success: function (data) {
            availableTags = data;
            availableTags = jQuery.map(data, function (n) {
                return (n.name);
            });
            console.log(availableTags);
            $(".deviceCatalog").autocomplete({
                source: availableTags
            });
        }
    })
};

Which gets data:

public string GetDeviceNames()
{
    var data = unitOfWork.deviceRepository
                              .Get()
                              .Select(w =>new {
                                                name= w.CatalogNo + " " + w.Name,
                                                Id=w.Id 
                                              })
                              .ToArray();
    return JsonConvert.SerializeObject(data);
}

As you can see it's getting Name + Id.

How to bind this all together to fulfill this requirement:

  • user can use autocomplete with name but Knockout will store an Id in observable
GôTô
  • 7,974
  • 3
  • 32
  • 43
szpic
  • 4,346
  • 15
  • 54
  • 85
  • You can see a working example of autocomplete+ko in this thread: http://stackoverflow.com/questions/23711542/not-able-to-select-bind-item-from-jquery-autocomplete-using-knockout-js – GôTô May 21 '14 at 08:27
  • I just pasted my solution :> But thanks! – szpic May 21 '14 at 08:28

1 Answers1

1

this is what I needed to do:

First: Unbind from that input:

<input id="DeviceId" class="form-control deviceCatalog" required />

Modify Ajax call: from:

$(".deviceCatalog").autocomplete({
    source: availableTags
});

to:

$(".deviceCatalog").autocomplete({
      source: availableTags,
      change: function (event, ui) 
           { 
               viewModel.DeviceTemp(ui.item.id);
           } 
      });

As You can see I added change event in which I modify the observable. As a result it stores the ID of an element.

Last but not least I needed to change my controller method: from:

var data = unitOfWork.deviceRepository.Get().Select(w =>new {name= w.CatalogNo + " " +w.Name, Id=w.Id }).ToArray();

to:

var data = unitOfWork.deviceRepository.Get().Select(w =>new {label= w.CatalogNo + " " +w.Name, id=w.Id }).ToArray();

I changed name to label. Now JQuery correctly see my label which should be used in autocomplete.

szpic
  • 4,346
  • 15
  • 54
  • 85