I try to use jQuery UI Autocomplete function to show some data and select it. But I see some error in the console I get a javascript error (item is undefined). My code is

jq version: jquery-ui-1.10.3.custom.min.js jq-ui version: jquery-1.10.2.min.js

 $("#searchterms").autocomplete({
            minLength: 2,
            source: '@(Url.RouteUrl("OrderSkuSearch"))',
            focus: function (event, ui) {
                $("#searchterms").val(ui.item.label);
                $("#productid").val(ui.item.id);
                console.log("focus: " + ui.item.id);
                return false;
            },
            select: function (event, ui) {
                $("#searchterms").val(ui.item.value);
                $("#productid").val(ui.item.id);
                console.log("select: " + ui.item.id);
                return false;
            },

            autoFocus: true,
            delay: 3000

        })
            .data("ui-autocomplete")._renderItem = function (ul, item) {
                //if ($("#productid").val() == "") {
                //    $("#productid").val(item.id);
                //}
                $("#productid").val(item.id);
                return $("<li>")
                .append("<a>" + item.value + ">" + item.label + "</a>")
                .appendTo(ul);
            };

The return type is list:

[{"label":"Build your own computer","value":"COMP_CUST","id":1}]

1 Answers

0
Twisty On

It's a little unclear what you are trying to accomplish. Consider the following example:

$(function() {
  var terms = [{
    label: "Label 1",
    value: "Value 1",
    id: 1001
  }, {
    label: "Label 2",
    value: "Value 2",
    id: 1002
  }, {
    label: "Label 3",
    value: "Value 3",
    id: 1003
  }];

  $("#searchterms").autocomplete({
    minLength: 2,
    source: terms,
    focus: function(event, ui) {
      $("#searchterms").val(ui.item.label);
      $("#productid").val(ui.item.id);
      console.log("focus: " + ui.item.id);
      return false;
    },
    select: function(event, ui) {
      $("#searchterms").val(ui.item.value);
      $("#productid").val(ui.item.id);
      console.log("select: " + ui.item.id);
      return false;
    },
    autoFocus: true,
    delay: 3000
  });
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div class="ui-widget">
  <label for="searchterms">Search: </label>
  <input type="text" id="searchterms" />
  <input type="text" id="productid" />
</div>

This seems to do what you want, yet I am not sure what Link you're trying to create.

Hope this helps.