1

I am using jquery autocomplete on a label/value list of mobile phones:

[ { label: "Samsung Galaxy S7", value: "Samsung Galaxy S7"}, 
  { label: "Samsung Galaxy S6", value: "Samsung Galaxy S6"},
.....
]

I would like to perform a research without specifing the series name, i.e. if user types "Samsung S7" autocomplete suggests "Samsung Galaxy S7"

I tried to modify the source as follow:

[ { label: "Samsung Galaxy S7 Samsung S7", value: "Samsung Galaxy S7"}, 
  { label: "Samsung Galaxy S6 Samsung S6", value: "Samsung Galaxy S6"},
.....
]

This code works but it is ugly, because the autocomplete menu shows "Samsung Galaxy S6 Samsung S6" instead of a simple "Samsung Galaxy S6"

Is there a way to perform research on a property while showing in the menu a different one?

gbalduzzi
  • 9,356
  • 28
  • 58

1 Answers1

2

You need to write your custom search logic using the source option. For a simple use case something like the following will do. See jQuery UI Autocomplete widget search configuration for more info.

Maybe you'll need a complex regex to handle edge cases (not necessary if you have a static/trust worthy data source).

$(document).ready(function() {

  var devices = [{
    label: "Samsung Galaxy S7",
    value: "Samsung Galaxy S7"
  }, {
    label: "Samsung Galaxy S6",
    value: "Samsung Galaxy S6"
  }];

  $("#devices").autocomplete({
    source: function(req, responseFn) {
      var words = req.term.split(' ');
      var results = $.grep(devices, function(device, index) {
        var sentence = device.label.toLowerCase();
        return words.every(function(word) {
          return sentence.indexOf(word.toLowerCase()) >= 0;
        });
      });
      responseFn(results);
    }
  });

});
input {
  margin-top: 100px;
}
<link href="https://code.jquery.com/ui/1.8.23/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
<input type="text" id="devices" />
Community
  • 1
  • 1
T J
  • 42,762
  • 13
  • 83
  • 138
  • It works fine, thanks! I didn't see that defining a function as source allowed to perform custom searches – gbalduzzi Jul 05 '16 at 13:08