Display autocomplete results by most accurate, not alphabetical

Display autocomplete results by most accurate, not alphabetical

Hi

The source for the Autocomplete is a PHP file that grabs the data from the database. The list is of business names.

The client needs the search to look for the users word/s any where within the business name. For instance the source could be "Wishing Well Care Home, Wellbeing Care Homes, Day Care Wellbeing, Wellbeing Clinic...". If the user starts typing in  "well" it will find the all results containing "well". The problem I have is if the user types in "Wellbeing", the results are alphabetical.

If you look at the screen grab I've attached you will see that the first result is "Dental Wellbeing". I want it to show any listings that START with "Wellbeing" first. So that a listing like "Wellbeing Clinic" shows first. Basically the most relevant listings are shown as priority. Even if the listing is just "Wellbeing", it doesn't get displayed first, as the results are alphabetical and not displayed by relevance.

I found this link, but the code differs from my own:

My Code
  1. $(function(){$("#BName").autocomplete({type:"POST",source:"lib/business_names_search.php",minLength:3,focus:function(e,t){$("#BName").val(t.item.label);$("#SPCode").val(t.item.value);return false},select:function(e,t){$("#BName").val(t.item.label);$("#SPCode").val(t.item.value);return false}}).data("ui-autocomplete")._renderItem=function(e,t){return $("<li>").append("<a>"+t.label+"</a>").appendTo(e)}})

jsfiddle Code

  1. $(document).ready(function () {
  2.     var source = ['wellcome', 'dental wellbeing', 'wellbeing home care', 'wellhome', 'wellbeing nursing home', 'wellbeing', 'Tim'];
  3.     $("input").autocomplete({
  4.         source: function (request, response) {
  5.             var term = $.ui.autocomplete.escapeRegex(request.term)
  6.                 , startsWithMatcher = new RegExp("^" + term, "i")
  7.                 , startsWith = $.grep(source, function(value) {
  8.                     return startsWithMatcher.test(value.label || value.value || value);
  9.                 })
  10.                 , containsMatcher = new RegExp(term, "i")
  11.                 , contains = $.grep(source, function (value) {
  12.                     return $.inArray(value, startsWith) < 0 &&
  13.                         containsMatcher.test(value.label || value.value || value);
  14.                 });
  15.            
  16.             response(startsWith.concat(contains));
  17.         }
  18.     });
  19. });

Any help will be appreciated.
G