1

I am working on auto complete and used this http://jqueryui.com/demos/autocomplete/#combobox

Now my query is that this api gives the user a flexibility to type and search the values of combo-box but due to this user can type anything.But is there any way to restrict the user from submitting wrong search query. This is because my combo-box is going to be used as a search criteria and its value is submitted to next page and due to this feature it submits wrong data to the page.

Thank you in advance... thanks

Ankur Verma
  • 5,793
  • 12
  • 57
  • 93

1 Answers1

1

You could try a custom matcher function to force a match or clear the field...

$("#input").autocomplete({ << initialise the autocomplete here >>})
.on('blur', function(event){
  // Grab the autocomplete object
  var autocomplete = $(this).data("autocomplete");
  var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i");
  // Iterate through the autocomplete list items to find any partial or full matches
  autocomplete.widget().children(".ui-menu-item").each(function() {
    var item = $(this).data("item.autocomplete");
    if (matcher.test(item.value || item)) {
      //There was a match
      matchcount++;
      autocomplete.selectedItem = item;
      return;
    }
  });
  if (autocomplete.selectedItem) {
    //if there was a match trigger the select event on that match
    autocomplete._trigger("select", event, {
      item: autocomplete.selectedItem
    });
  //there was no match, clear the input
  } else {
      $(this).val('');
  }
});
mwotton
  • 2,170
  • 18
  • 36
  • can you implement on JSfiddle..and I am not getting $("#input").autocomplete({ << initialise the autocomplete here >>}) what to initialize here? – Akki Jan 18 '13 at 10:48
  • Maybe this is a clearer/easier answer: http://stackoverflow.com/questions/2909077/jquery-ui-autocomplete-disallow-free-text-entry – Meetai.com Sep 25 '13 at 14:36