1

I am using datalist for my autocomplete field. Its working fine. I have the values james,reeta and mary in my list, if i enter "r" in my auto complete box, it returns the values reeta and mary because mary also contain the letter "r". but i dont want my auto complete to work like this. i just want only reeta not mary it means the values which has the entered letter as the starting letter.

Sangeetha Krishnan
  • 941
  • 1
  • 12
  • 17
  • I found it weird that autocomplete datalist works as you demanded i.e. on entering 'r' it shows only reeta and not marry in Chrome and IE-10 (Lower version of IE doesn't support datalist) while only Mozilla Firefox displayed both reeta and mary on hitting 'r'. Please share if you figured out that whats the reason behind this – sumitb.mdi Jun 19 '13 at 14:17

1 Answers1

1

Use source option to implement your own search:

var dataSource = ['mary', 'reeta', 'james'];

$("input").autocomplete({
    minLength: 1,
    source: function(request, response) {

        var matcher = new RegExp( '^' + $.ui.autocomplete.escapeRegex(request.term), "i" );
        var filteredData = $.grep( dataSource, function(value) {
            return matcher.test( value.label || value.value || value );
        });
        response(filteredData);
    }
});

example http://jsfiddle.net/AU92X/8/

Or you can even make it global just by rewriting $.ui.autocomplete.escapeRegex:

var dataSource = ['mary', 'reeta', 'james'];

$("input").autocomplete({
    minLength: 1,
    source: dataSource
});

var escapeRegexp = $.ui.autocomplete.escapeRegex;
$.extend( $.ui.autocomplete, {
    escapeRegex: function( value ) {
        return '^' + escapeRegexp(value);
    }
});

example http://jsfiddle.net/AU92X/10/

claustrofob
  • 5,448
  • 2
  • 19
  • 22