Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Autocomplete UI Search At Beginning

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 control that returns 15,000 and their corresponding PKs. value is the name and Id is the integer PK.The code below works but since I'm searching through 15,00 strings that matches any where in the string it is too slow. I've seen this post, link, but I couldn't figure out how to do without losing the Id field in the source.

I need the search to only match the beginning of value in data.d without losing the Id field. This is an ASP.Net app but I don't think it matters. Ideas?

$("#companyList").autocomplete({
              minLength: 4,
              source: data.d,
              focus: function(event, ui) {
                  $('#companyList').val(ui.item.value);
                  return false;
              },
              select: function(event, ui) {
                  $('#companyList').val(ui.item.value);
                  $('#<%= hdnCompanyListSelectedValue.ClientID %>').val(ui.item.Id);
                  return false;
              }
          });
like image 618
mike Avatar asked Apr 26 '11 13:04

mike


1 Answers

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

like image 76
jk. Avatar answered Oct 04 '22 16:10

jk.