10

*Story:

I have a site with 2 search bars, where users can search a school then a class within that school via jQuery autocomplete. All my data is in a LOCAL json array, for example:

var schools = [{"label": Boston University, "value": Boston University, "nickname": BU}]

*Problem:

When searching, I want to match user's input not just to "label" but to "nickname" as well, so that school is searchable by both "Boston University" and "BU". Here's my code now:

$(document).ready(function(){
  $("#school").autocomplete({
    appendTo: ".custom-autocomplete",
    source: schools,
    minLength: 0,
    select: function( event, ui ) {
      $("#class").autocomplete({
        appendTo: ".custom-autocomplete",
 source: courses,
 minLength: 2,
 select: function( event, ui ) {
          $('#submit_header_form').attr('class','submit_header_form');
 }
      });
    });
 });

I know we can use PHP on remote data to achieve this result, but I need to use a local array to speed up the search because I have a lot of classes within each school.

Since I'm a newbie code and the stack is fully functional now, a quick fix would be ideal. Thanks everyone for your help!

1
  • A common solution is to include the nicname in the result name. This is a common problem in the airline industry also, for example, check out this site flightstats.com/go/Home/home.do which has airports such as (YYZ) Toronto International. Posting as a comment because this is not the technical answer. Commented Jan 17, 2011 at 21:55

1 Answer 1

22

You can do it by supplying source as a callback. There is an example on jQuery UI website, but you can just modify standard implementation.

source: function (request, response) {
    var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
    response($.grep(schools, function(value) {
        return matcher.test(value.value)
            || matcher.test(value.nickname);
    }));
}

Here's a fiddle: http://jsfiddle.net/h5E6C/

Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what I was looking for. Thanks so much German Rumm! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.