jQuery autocomplete displaying all elements instead of typed elements

21 Views Asked by At

I am trying to implement autocomplete using jQuery. Tried the example https://jqueryui.com/autocomplete/ and worked fine. But when I am getting the same response from the server, it is displaying all the elements instead of typed search.

Now I try to send the list from the server(Controller)

List<String> data2 = new ArrayList<String>();   
        data2.add("ActionScript");
        data2.add("AppleScript");
        data2.add("BASIC");
        data2.add("Clojure");
        data2.add("JavaScript");
        data2.add("Python");
        data2.add("Ruby");
        
@RequestMapping(value = "/invoiceNumberData2.html", method = RequestMethod.GET , produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody List<String> getLicenseNumber2(@RequestParam String term) {
        
        return data2;

    }

If I pass JsonString, getting "Uncaught TypeError: Cannot use 'in' operator to search for 'length' in ["ActionScript","AppleScript","BASIC","Clojure","JavaScript","Python","Ruby"]"

[![$(document).ready(function() {
      
         $("#licenseNumber").autocomplete({
          dataType: 'json',
          minLength: 3,
            source: function (request, response) {
            jQuery.get("/dltcEPay/secure/invoiceNumberData2.html", {
                term: request.term
            }, function (data) {
                console.log("Coming from server: " + data); 
                var JsonString = JSON.stringify(data);
                 console.log("After converting to json array: " + JsonString);   
                 var JsonObject = JSON.parse(JsonString);        
                 console.log("After converting to json OBJECT: " + JsonObject);             
             
            response(JsonObject);
               
            });
            },
       
    });

});][1]][1]

Tried converting the response to JSON Object. Error was gone but results are not getting filtered, no matter what I type, displaying all elements. Pleases see the pick.

Console Output as below:

Coming from server: ActionScript,AppleScript,BASIC,Clojure,JavaScript,Python,Ruby

After converting to json array: ["ActionScript","AppleScript","BASIC","Clojure","JavaScript","Python","Ruby"]

After converting to json OBJECT: ActionScript,AppleScript,BASIC,Clojure,JavaScript,Python,Ruby

Final output

1

There are 1 best solutions below

0
user3067524 On

OMG, above Code is just fine. I will have to add a filter as below.

if (data) {
                // Filter data on the client side if necessary
                var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i");
                var filteredArray = $.grep(data, function(item) {
                    return matcher.test(item);
                });
                response(filteredArray);
            } else {
                response([]);
            }