Jquery Autocomplete custom data and display not working when multiple fields used

13 views Asked by At

So, I'm trying to use jquery autocomplete in my flight search form which has an origin and destination field which I've attached this autocomplete functionality by using the class .autocomplete.

I want to display the drop-down entries in a custom format and I've used the following javascript code for this

 // Autocomplete configurations
  const airports = [
    {
      value: "CMB",
      label: "Colombo Bandaranayake",
      country: "Sri Lanka",
    },
    {
      value: "DEL",
      label: "Delhi Indira Gandhi",
      country: "India",
    },
    {
      value: "LHR",
      label: "London Heathrow",
      country: "Engaland, UK",
    },
  ];

  $(".autocomplete")
    .autocomplete({
      source: airports, 
      minLength: 3,
      focus: function (event, ui) {
        event.target.value = ui.item.value;
        return false;
      },
      select: function (event, ui) {
        event.target.value = ui.item.value;
        return false;
      },
    })
    .autocomplete("instance")._renderItem = function (ul, item) {
    return $("<li>")
      .append(
        "<div>" +
          item.label +
          " (" +
          item.value +
          ")<br>" +
          item.country +
          "</div>"
      )
      .appendTo(ul);
  };

However the custom dropdown is only visible for the origin field not the destination field. I have used the same class .autocomplete for the both field in my html

The function .autocomplete("instance")._renderItem() is not getting invoked for the destination field, unfortunately i couldn't find any docs on this function in details so i'd be glad if you guys can shed some light on the usage of this function. If I'm using it incorrectly do let me know. I

Thanks in advance

Solution Found the solution myself. Posting this hoping this would aid someone on their quest.

Initial autcomplete() call returns multiple elements thus we should iterate it using each() passing in a callback which in turns call the autocomplete('instance'). Though I have no clear view of this latter function. Prey, some noble person could shed some light into this function i'd highly appreciate.

$(".autocomplete")
    .autocomplete({
      source: airports, //iata,
      minLength: 3,
      focus: function (event, ui) {
        event.target.value = ui.item.value;
        return false;
      },
      select: function (event, ui) {
        event.target.value = ui.item.value;
        return false;
      },
    })
    .each((i, e) => {
      $(e).autocomplete("instance")._renderItem = (ul, item) => {
        return $("<li>")
          .append(
            "<span>" +
              item.label +
              "</span><br><span>" +
              item.country +
              "</span>"
          )
          .appendTo(ul);
      };
    });
0

There are 0 answers