Using JQuery AutoComplete UI ,1.8, I need to change the search so it matches only at the start of the string. Background my source comes from an ajax call that I don\'t cont
Here is a possible solution for you. You guys were on the right track. I used a json string as the datasource and I know the text I want to match is in the item.label field. It might be in item.value for you: Input fields:
<input type="text" id="state" name="state" />
<input
readonly="readonly" type="text" id="abbrev" name="abbrev" maxlength="2"
size="2"/>
<input type="hidden" id="state_id" name="state_id" />
jQuery
var states = [{"id":"1","label":"Armed Forces Americas (except Canada)","abbrev":"AA"},{"id":"2","label":"Armed Forces Africa, Canada, Europe, Middle East","abbrev":"AE"},{"id":"5","label":"Armed Forces Pacific","abbrev":"AP"},{"id":"9","label":"California","abbrev":"CA"},{"id":"10","label":"Colorado","abbrev":"CO"},{"id":"14","label":"Florida","abbrev":"FL"},{"id":"16","label":"Georgia","abbrev":"GA"},{"id":"33","label":"Northern Mariana Islands","abbrev":"MP"},{"id":"36","label":"North Carolina","abbrev":"NC"},{"id":"37","label":"North Dakota","abbrev":"ND"},{"id":"43","label":"New York","abbrev":"NY"},{"id":"46","label":"Oregon","abbrev":"OR"}];
$("#state").autocomplete({
source: function(req, response) {
var re = $.ui.autocomplete.escapeRegex(req.term);
var matcher = new RegExp( "^" + re, "i" );
response($.grep( states, function(item){
return matcher.test(item.label); }) );
},
minLength: 2,
select: function(event, ui) {
$('#state_id').val(ui.item.id);
$('#abbrev').val(ui.item.abbrev);
}
});
And here is a working example: http://www.jensbits.com/demos/autocomplete/index3.php