Ankur Verma
Ankur Verma

Reputation: 5933

Autocomplete Jquery with user restriction

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

Upvotes: 1

Views: 329

Answers (1)

mwotton
mwotton

Reputation: 2200

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('');
  }
});

Upvotes: 1

Related Questions