AutoComplete in jQuery with dynamically added elements works only in first input field

135 Views Asked by At

I have a scenario where when we load the page for the first time it will have an input field along with a button to add more rows. In my case, the autocomplete works on the very first row and it is not working on the rows added using the button.

The code is as follows

  // In Js file

  $(".autocomplete").each((_, item) => {
    const $item = $(item);
    $item.typeahead(
      {
        minLength: 1,
        highlight: true,
      },
      {
        name: $item.attr("test-data"),
        source: async (keywords, syncResults, asyncResults) => {
          return $.ajax({
            data: { keywords: keywords },
            dataType: "json",
            success: (response) => {
              return asyncResults(response.items);
            },
            type: "post",
            url: window.URLS["autocomplete"][$item.attr("test-data")],
          });
        },
        limit: 10,
        templates: {
          notFound: "No match",
          pending: "Loading...",
          suggestion: (item) => {
            return `<div>${item}</div>`;
          },
        },
      },
    );
  });

// To handle add button click
$data.on("click", ".insert", () => {
    $data.append($(document.importNode($data.get(0).querySelector("template").content, true)));
});
// This is inside a twig file to add  a new input when the add button is clicked

<input
    class="autocomplete block"
    test-data="test"
    type="text"
    value="{{ value.event }}"
/>

Can anyone help me out?

1

There are 1 best solutions below

2
mplungjan On

You can have this

const atc = () => {    
  $(".autocomplete")
  .filter((_, item) => { return !$(item).is(".tt-input") }) // ignore already assigned autocompletes
  .each((_, item) => {
    const $item = $(item);
    ...
  });
}

and add

$(function() {
  $("#add")..on("click",() => {
     // add the field
     atc()
  });
  atc()
})