Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

auto complete exact match from start using jquery autocomplete from simple array

How do I enable exact match from start of string using jquery autocomplete with input from simple array?

If i have the following in an array:

  • smart
  • oversmart
  • smartland
  • undersmart
  • verysmart

And if I am typing "sma..." in the text input, i must be shown only smart and smartland, not the others.

like image 387
Vijai Krishna Avatar asked May 05 '12 17:05

Vijai Krishna


2 Answers

You just need to modify source parameter as a function to suit your needs. Like this:

http://jsfiddle.net/UKgD6/


Update: Adding code to answer:

var acList = ['smart', 'oversmart', 'smartland', 'undersmart', 'verysmart'];
$('#ac').autocomplete({
    source: function (request, response) {
        var matches = $.map(acList, function (acItem) {
            if (acItem.toUpperCase().indexOf(request.term.toUpperCase()) === 0) {
                return acItem;
            }
        });
        response(matches);
    }
});
like image 197
keune Avatar answered Sep 23 '22 13:09

keune


The way to do this is documented at http://api.jqueryui.com/autocomplete/

<script>
    var tags = [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ];
    $( "#autocomplete" ).autocomplete({
      source: function( request, response ) {
              var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" );
              response( $.grep( tags, function( item ){
                  return matcher.test( item );
              }) );
          }
    });
</script>
like image 41
Jonathan Vance Avatar answered Sep 25 '22 13:09

Jonathan Vance