6

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;
              }
          });
mike
  • 93
  • 2
  • 5
  • link that disappeared, http://stackoverflow.com/q/2382497/714105 – mike Apr 26 '11 at 13:54
  • You're right - It doesn't matter that it's an ASPNET app. What do you mean by *I couldn't figure out how to do without losing the Id field in the source*? The source can be a function; you need to replace your source with a fn, which scans through the `data.d` and finds what you want, then invokes the `responseFn` with the result set. Eg, instead of `source: data.d,` you need to supply `source: function(req,responseFn){...}` It's not clear what problem you're having with "losing the id". – Cheeso Apr 26 '11 at 14:02
  • Maybe what you mean is, you want the id to be available in the `select:` fn when it gets invoked, is that right? In that case you may also want to patch the `_renderMenu` and `_renderItem` fns, to insert the id into the `
  • ` element for each value - maybe use a custom attribute. For how to do this, see http://stackoverflow.com/questions/2435964/jqueryui-how-can-i-custom-format-the-autocomplete-plug-in-results/2436493#2436493
  • – Cheeso Apr 26 '11 at 14:06
  • if i change source this this below 1) it doesn't work 2) the only way I could make it work was to only pass in the names which meant I wouldn't have the Id in the select. source: function(req, responseFn) { var re = $.ui.autocomplete.escapeRegex(req.term); var matcher = new RegExp( "^" + re, "i" ); var a = $.grep( data.d, function(item,index){ return matcher.test(item); }); responseFn( a ); } – mike Apr 26 '11 at 14:08
  • @Cheeso, correct on your 2nd comment, I need the Id for the select – mike Apr 26 '11 at 14:09
  • I was also looking at the search event but I couldn't tell which methods applied to ui, so I can't tell what's in there. – mike Apr 26 '11 at 14:15