question

AsistanceRequest-0783 avatar image
0 Votes"
AsistanceRequest-0783 asked YijingSun-MSFT commented

autocomplete only works the second time

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



dotnet-aspnet-core-mvcdotnet-aspnet-mvc
problem.jpg (51.6 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

BruceBarker-8516 avatar image
0 Votes"
BruceBarker-8516 answered AsistanceRequest-0783 commented

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")");



· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

im not sure if its my computer, my server management studio, or my visual studio but for some reason ajax code that looks like it should work doesnt 9 times out of 10 and unfortunatly this seems to be one of the 9.
your code doesnt work for me, it might for you but i just cant get it to do anything so to be sure i added 1' and '2' alerts to the code with the 1 before and the 2 after the ajax

get the 1 but not the 2. no errors on my console and no autocomplete dropdown

is it possible to replace the ajax with getJSON?

0 Votes 0 ·
YijingSun-MSFT avatar image
0 Votes"
YijingSun-MSFT answered YijingSun-MSFT commented

Hi @AsistanceRequest-0783 ,
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.

· 4
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

am i using your code properly? i had attempted replacing my original code above with:
var url = '@Url.Action("ItemArray")';
var confirm = $("#ItemName").val()
$("#ItemName").autocomplete({
source: function (confirm, response) {
$.getJSON(url, { confirm: confirm.term }, function (data) {
response($.map(data, function (el) {
return {
label: el.TagName,
value: el.TagId
};
}));
});
},
});
to no avail, so i tried adding
$(document).ready(function () {

which changed nothing. let me know if there is somthing im missing

0 Votes 0 ·
YijingSun-MSFT avatar image YijingSun-MSFT AsistanceRequest-0783 ·

Hi @AsistanceRequest-0783 ,
I have posted is Jquery UI autocomplete. It's different with the autocomplete method. Your old way does not support calling autocomplete more than once for the same input field. So,I suggest you could use Jquery UI autocomplete.It need jquery js. You could check if you have error with pressing F12.
https://jqueryui.com/autocomplete/
Best regards,
Yijing Sun

0 Votes 0 ·

your link was helpful but i still am unable to get the dropdown to work. here is the code i made based off your link:

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

here is the error i have after pressing F12:error


0 Votes 0 ·
problem.jpg (105.4 KiB)
Show more comments