Search code examples
jqueryresponse

jQuery UI auto-complete response index problem


I am using the jQuery ui-complete library which calls an endpoint via get request to populate a list of suggested autors:

$("#author-name").autocomplete({
                source: "/authors/get.json",
                minLength: 5,
                select: function(event, ui) {
                    event.preventDefault();
                    $("#author-name").val(ui.item.label);
                    $("#author-id").val(ui.item.value);
                }

});

The issue is the format of the reply, which is wrapped inside an indexed array as follows:

{
    "reply": [
        {
            "value": 9,
            "label": "Joe Bloggs"
        },
    ]
}

Is it possible to tell the response to be treated from the reply object, something like:

select: function(event, ui.reply) {

I've read the api docs on the library but couldn't find a solution.


Solution

  • source is expecting an array so you are going to have to adjust what you are assigning to it.
    In the example below, I simply made a new function to get the data then access the reply array and that is what I pass to Autocomplete source

    $(document).ready(function() {
    
      function getResponse() {
        var response = {
          "reply": [{
              "value": 9,
              "label": "Joe Bloggs"
            },
            {
              "value": 10,
              "label": "foo"
            },
          ]
        }; // in your case: read data from /authors/get.json
    
        return response.reply;
      }
    
      $("#tags").autocomplete({
        source: getResponse(),
        select: function(event, ui) {
          event.preventDefault();
          console.log(ui.item.value);
          console.log(ui.item.label);
        }
      });
    });
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" />
    
    <div class="ui-widget">
      <label for="tags">Tags: </label>
      <input id="tags">
    </div>