autocomplete only works the second time

Asistance Request 21 Reputation points
2021-07-08T20:02:11.643+00:00

im trying to repurpose the code found here: https://www.w3schools.com/howto/howto_js_autocomplete.asp
the only difference is i wanted to use my database instead of a hard-coded string for the most part i was successful with

    $("#ItemName").on("keyup", function () {  
                var url = '@Url.Action("ItemArray")';  
                var confirm = $(this).val()  
                $.getJSON(url, { confirm: confirm}, function (response) {  
                    if (!(response.length === 0)) {  
                        autocomplete(document.getElementById("ItemName"), response);  
                    }  
                });  
            });  

here is my problem:
problem

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,148 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,248 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce Barker 801 Reputation points
    2021-07-08T21:24:54.243+00:00

    the sample code does not support calling autocomplete more than once for the same input field. each time you call it adds more events.

    you should modify the autocomplete code to make the ajax call. just pass the url in:

    function autocomplete(inp, url) {  
      /*the autocomplete function takes two arguments,  
      the text field element and an array of possible autocompleted values:*/  
      var currentFocus;  
      /*execute a function when someone writes in the text field:*/  
      inp.addEventListener("input", function(e) {  
          var val = this.value;;  
          /*close any already open lists of autocompleted values*/  
          closeAllLists();  
          if (!val) { return false;}  
      
          $.ajax(url, {confirm:val}, function(arr) {   
              var a, b, i;  
              if (arr.length == 0) return;  
              currentFocus = -1;  
              /*create a DIV element that will contain the items (values):*/  
              a = document.createElement("DIV");  
              a.setAttribute("id", this.id + "autocomplete-list");  
              a.setAttribute("class", "autocomplete-items");  
              /*append the DIV element as a child of the autocomplete container:*/  
              this.parentNode.appendChild(a);  
              /*for each item in the array...*/  
              for (i = 0; i < arr.length; i++) {  
                /*check if the item starts with the same letters as the text field value:*/  
                if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {  
                  /*create a DIV element for each matching element:*/  
                  b = document.createElement("DIV");  
                  /*make the matching letters bold:*/  
                  b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";  
                  b.innerHTML += arr[i].substr(val.length);  
                 /*insert a input field that will hold the current array item's value:*/  
                 b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";  
                /*execute a function when someone clicks on the item value (DIV element):*/  
                 b.addEventListener("click", function(e) {  
                     /*insert the value for the autocomplete text field:*/  
                     inp.value = this.getElementsByTagName("input")[0].value;  
                     /*close the list of autocompleted values,  
                         (or any other open lists of autocompleted values:*/  
                  closeAllLists();  
              });  
              a.appendChild(b);  
            }  
          }  
      });  
    

    then call like:

    autocomplete(  
       document.getElementById("ItemName"),   
       "@Url.Action("ItemArray")");  
    
    
    
      
    

  2. Yijing Sun-MSFT 7,066 Reputation points
    2021-07-09T02:33:50.773+00:00

    Hi @Asistance Request ,
    As far as I think,you could use $getJSON. You could change the autocomplete widget's source parameter to be a function.Just like this:

    $("#ItemName").autocomplete({  
        source: function (request, response) {  
            $.getJSON(url, { term: request.term }, function (data) {  
                response($.map(data, function (el) {  
                    return {  
                        label: el.TagName,  
                        value: el.TagId  
                    };  
                }));  
            });  
        },  
        /* other autocomplete options */  
    });  
    

    Best regards,
    Yijing Sun


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our  documentation  to enable e-mail notifications if you want to receive the related email notification for this thread.