Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jqueryui autocomplete filter results (from remote datasource ) that "begin with" input

I'm using jquery autocomplete with multiple results and a remote datasource. I'm able to pull the data remotely and select multiple results. But the results list doesn't update based on the first 2 characters input, and the jQueryUI documentation is thin on this issue.

I've researched around, and found this answer here on SO and want to integrate it with the rest of my function, but it doesn't update the results list. Independently, the SO answer works fine, but not when integrated with multiple results and a remote datasource.

From the autocomplete/remote source/multiple function (truncated). This part works fine:

.autocomplete({
                source: function( request, response ) {                            
                     $.ajax({
                        url: "/controller/myfunction",
                        dataType: "json",
                        data: request,
                        success: function(data){
                        if(data.response == 'true') {
                            response(data.message);
                            }
                        }
                    });
                },

Possible solution on SO: (works fine independently, but not with the jquery/remote/multiple code):

var wordlist= [ "about", "above", "within", "without"];

$("#input1").autocomplete({
    source: function(req, responseFn) {
        var re = $.ui.autocomplete.escapeRegex(req.term);
        var matcher = new RegExp( "^" + re, "i" );
        var a = $.grep( wordlist, function(item,index){
            return matcher.test(item);
        });
        responseFn( a );
    }
});

I need to integrate this solution with my code.

like image 377
chowwy Avatar asked Oct 28 '12 22:10

chowwy


2 Answers

From jQuery UI Autocomplete: Search from Beginning of String you can try:

$("#YOUR_TEXT_INPUT").autocomplete({
    source: function(req, response) { 
       $.ajax({
        url: "/controller/myfunction",
        dataType: "json",
        success: function( data ) {
            var re = $.ui.autocomplete.escapeRegex(req.term);
            var matcher = new RegExp( "^" + re, "i" );
            response($.grep(data, function(item){return matcher.test(item.value);}) );
            }
        });
     },
      minLength: 2,
      select: function(event, ui) {
          //custom select function if needed
       }
    });
like image 168
jk. Avatar answered Nov 15 '22 06:11

jk.


jQuery autcomplete sends what the user has typed in as a HTTP parameter, so you can use that to alter the results that you fetch from the DB.

Here is an example (in CakePHP). It gets the "term" parameter, which contains what the user typed in, and it uses that to generate the DB query.

like image 35
Tom Dalling Avatar answered Nov 15 '22 06:11

Tom Dalling