George Duckett
George Duckett

Reputation: 32428

Search field other than value field

I have a jquery autocomplete widget that is displaying items with custom data.

They all have a value, and description.
Currently the value is inserted into the textbox when an item is clicked and the value of an item is what is searched

What I'd like to do is have the filter use both the value and the description when filtering items to display, but keep only the value being inserted.

How can I achieve this?

Upvotes: 0

Views: 69

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074148

If you give the autocompleter an array of objects with value and label (rather than description) properties, it will do the filtering for you, but only on the label (not the value).

If you specify a function for the source option, you're expected to do the filtering yourself. You receive a request argument (an object with a term property) and a response argument (a function to call back with the results). You then return relevant results yourself, using any kind of search you like (e.g., you can search both value and description in your code).

E.g., loosely:

$("some selector").autocomplete({
    // ...other options...
    source: function(request, response) {
        var matches = [];
        /* ...search for matches in your data using `request.term`,
           add them to `matches`...
        */
        response(matches);
    }
});

The array you return can be just strings, or it can be objects with value and label properties. The label will be shown, the value will be used when selected.

So for example, here's one using a (short) list of airports, where when you type it checks both the value (the airport code) and the description (the airport name): Live copy | source

jQuery(function($) {
  var data = [
    {value: "ORD", description: "Chicago O'Hare"},
    {value: "LHR", description: "London Heathrow"},
    {value: "SFO", description: "San Francisco International"}
  ];

  $("#theInput").autocomplete({
    source: function(request, response) {
      var capterm = request.term.toUpperCase();
      var matches = $.map(data, function(entry) {
        if (entry.value.toUpperCase().indexOf(capterm) !== -1 ||
            entry.description.toUpperCase().indexOf(capterm) !== -1) {
          return {
            value: entry.value,
            label: entry.value + " - " + entry.description
          };
        }
      });
      response(matches);
    }
  });
});

So typing "or" or "chic" will show you "ORD - Chicago O'Hare", and selecting it will put "ORD" in the field. Typing "san" or "sfo" will show you "SFO - San Francisco International" and selecting it will put "SFO" in the field.

Upvotes: 1

Related Questions