Home > Software engineering >  jQuery UI Autocomplete in $.each loop not showing results from first iteration
jQuery UI Autocomplete in $.each loop not showing results from first iteration

Time:09-18

I am using "jQuery UI Autocomplete" to filter the JSON data, I am using following code for it

<input type="text" name="searchKeywords" id="ninecSearchKeywords" placeholder="How To...">

and then JS as

jQuery(document).ready(function($){
        
    $.getJSON("apiUrl", function(data){

        $.each(data, function(key, value){
            
            $("#ninecSearchKeywords").autocomplete({
              source: value.keys,
              autoFocus: true,
              select: function (event, ui) {
                window.location = value.pageLink;
              }
             });
            
        });
    });

});

and JSON Data is

[
    {
        pageID: "454",
        pageLink: "url",
        sectionID: "a599d36c4c7a71ddcc1bc7259a15ac3a",
        anchorLink: "anchor1",
        keys: [
            "Result 1",
            "Result 2",
            "Result 3"
        ]
    },
    {
        pageID: "455",
        pageLink: "url",
        sectionID: "8d993394c892dcaa8683dc4ba4fae21d",
        anchorLink: "anchor2",
        keys: [
            "Result 4",
            "Result 5",
            "Result 6"
        ]
    },
    {
        pageID: "456",
        pageLink: "url",
        sectionID: "dce6920a3408ae9a8e61b75a4e5fd6ca",
        anchorLink: "anchor3",
        keys: [
            "Result 7",
            "Result 8",
            "Result 9"
        ]
    }
]

This is working fine for #2 and #3 iteration and I am able to search for Result 4 to Result 9 but for the first iteration i.e. Result 1,2 and 3 no results are showing in dropdown.

Can anyone knows what went wrong here?

CodePudding user response:

The autocomplete source will not get updated inside loop. Create the data first and then add the source to autocomplete.

jQuery(document).ready(function($){
        
    $.getJSON("apiUrl", function(data){
        var keys = [];
        var keyLinkMap = {};
        $.each(data, function(key, value){
            for(let i = 0; i <= value.keys.length; i  ) {
                keys.push({label: value.keys[i], value:value.pageLink});            
            }
        });

        $("#ninecSearchKeywords").autocomplete({
              source: keys,
              autoFocus: true,
              select: function (event, ui) {
                window.location = value.pageLink;
              }
         });
    });

});
  • Related