Rtra
Rtra

Reputation: 522

jQuery autocomplete list not showing up

I have the following code but and its return data but the problem is ui-list is not showing/populating up I don't know what I am doing wrong?

$("input#ProdDesc").autocomplete({
  autoFocus: true,
  source: "includes/modProducts/search-products.php",
  minLength: 1,
  select: function(event, ui) {
    var item = ui.item;
    if (item) {
      $(this).closest('.row').find('input#ProdDesc').val(item.prod_name);
      $(this).closest('.row').find('input#prodctCode').val(item.prod_code);

    }
  }
});

Returning Data from PHP

[{
  "prod_code": "SPC-00001",
  "prod_name": "Testing Product Name1"
}, {
  "prod_code": "SPC-00002",
  "prod_name": "Product Name Again "
}]

ui-list items are showing like this:

enter image description here

Upvotes: 1

Views: 3923

Answers (1)

According to Terry's comment, your url should respond with the appropriate format:

[{label: "Testing Product Name1", value: "SPC-00001"}]

In case you can't modify the response of your URL, you can try this:

$(function() {
  $("input#ProdDesc").on("keypress", function() {
    $.ajax({
      url: "https://gist.githubusercontent.com/dannyjhonston/f4ffea60e7dc86a2d8dadfe477870294/raw/aec441e65a6e9e535feef16b9e970b4276baf346/products.json",
      type: "GET"
    }).done(function(response) {
      // response = [{"prod_code":"SPC-00001","prod_name":"Testing Product Name1"},{"prod_code":"SPC-00002","prod_name":"Product Name Again"}].
      var result = [],
        i, data = JSON.parse(response),
        len = data.length;
      for (i = 0; i < len; i++) {
        result.push({
          label: data[i].prod_name,
          value: data[i].prod_code
        });
      }

      // result = [{"label":"Testing Product Name1","value":"SPC-00001"},{"label":"Product Name Again","value":"SPC-00002"}].
      $("input#ProdDesc").autocomplete({
        autoFocus: true,
        source: result,
        minLength: 1,
        select: function(event, ui) {
          var item = ui.item;
          if (item) {
            console.log(item);
          }
        }
      });
    });
  });
});
.as-console-wrapper .as-console {
  background: linear-gradient(#fff, #818eb3);
}
<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>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<input id="ProdDesc" type="text" />

Upvotes: 2

Related Questions