0

I am working on JQueryUI autocomplete and would like a slightly different behavior than the default. I have an array of strings:

var json = ["Atlanta", "Chicago", "Little Rock", "RockFord", "Rhode Island"];

I would like the following results when I input the following to autocomplete.

Type: "R"

Actual Result:

Little Rock

Rhode Island

RockFord

Expected Result:

Rhode Island

RockFord

Little Rock

Type: Rock

Actual Result:

Little Rock

RockFord

Expected Result:

RockFord

Little Rock

Here's my jsFiddle

I would like the results to be ordered alphabetically first followed by matches in other words. I looked at this link but that only gets me the alphabetical ordering. When I type in "Rock" I would get only RockFord.

Any ideas?

Community
  • 1
  • 1
user1527762
  • 847
  • 4
  • 11
  • 27

1 Answers1

2

Try utilizing ._renderMenu , $.grep()

var json = ["Alabama",
  "Alaska",
  "Arizona",
  "Arkansas",
  "California",
  "Colorado",
  "Connecticut",
  "Delaware",
  "Florida",
  "Georgia",
  "Hawaii",
  "Idaho",
  "Illinois",
  "Indiana",
  "Iowa",
  "Kansas",
  "Kentucky",
  "Little Rock",
  "Louisiana",
  "Maine",
  "Maryland",
  "Massachusetts",
  "Michigan",
  "Minnesota",
  "Mississippi",
  "Missouri",
  "Montana",
  "Nebraska",
  "Nevada",
  "New Hampshire",
  "New Jersey",
  "New Mexico",
  "New York",
  "North Carolina",
  "North Dakota",
  "Ohio",
  "Oklahoma",
  "Oregon",
  "Pennsylvania",
  "RockFord",
  "Rhode Island",
  "South Carolina",
  "South Dakota",
  "Tennessee",
  "Texas",
  "Utah",
  "Vermont",
  "Virginia",
  "Washington",
  "West Virginia",
  "Wisconsin",
  "Wyoming",
];

json.sort();

$("input").autocomplete({
  source: json
}).data("ui-autocomplete")._renderMenu = function(ul, items) {
  var that = this;
  var val = that.element.val();
  $.each($.grep(items, function(value, key) {
    return new RegExp(val.toLowerCase())
           .test(value.value.toLowerCase().slice(0, val.length))
  }), function(index, item) {
    that._renderItemData(ul, item);
  });
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script type="text/javascript" src="https://code.jquery.com/ui/1.9.2/jquery-ui.js">
</script>
<input type="text" />

jsfiddle http://jsfiddle.net/Gm9Bz/75/


See also _renderMenu(ul, items) , jQueryUI: how can I custom-format the Autocomplete plug-in results? , Override both _renderItem and _renderMenu

Community
  • 1
  • 1
guest271314
  • 1
  • 10
  • 82
  • 156