Jquery Autocomplete from json list all elements

北城以北 提交于 2019-12-11 11:50:52

问题


In my script to autocomplete I set a json file:

SCRIPT

<script type="text/javascript">
  $("#tags").autocomplete({
    source: function(request, response) {
      $.ajax({
        url: "test.json",
        dataType: "json",
        data: { term: request.term },
        success: function(data) {
          response($.map(data, function(item) {
            return { label: item.name_test };
          }));
        }
      });
    }
  });
</script>

HTML

<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
</div>

The JSON file

[{
  "id_test": "7",
  "name_test": "Tejido",
  "price": "65"
}, {
  "id_test": "8",
  "name_test": "Semen",
  "price": "120"
}, {
  "id_test": "6",
  "name_test": "Saliva",
  "price": "20"
}, {
  "id_test": "2",
  "name_test": "Analisis urinario",
  "price": "150"
}, {
  "id_test": "3",
  "name_test": "Analisis sanguineo",
  "price": "1502"
}, {
  "id_test": "4",
  "name_test": "Analisis fecal",
  "price": "20"
}]

But when I type a name into the input, all the elements are listed.

What is my error?


回答1:


When you use a remote source, as your code is using, you must need to filter the results in the server side or in the success callback from the ajax call. In your case you can use something like:

...
success: function (data) {
    var tag_val = $("#tags").val();
    response($.map(data, function (item) {

        //filtering results....
        if (item.name_test.indexOf(tag_val) != -1) {
            return {
                label: item.name_test
            };
        }
    }));
}


来源:https://stackoverflow.com/questions/26936380/jquery-autocomplete-from-json-list-all-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!