Jakub
Jakub

Reputation: 20475

jQuery/UI Auto complete but only allow existing words to be typed in

Hopefully I am explaining this correctly, I have a long predefined list of items (products in my db) and I would like the user to be able to type and auto complete a product, however if that product / word is NOT in the list, I don't want to allow additional characters to be typed. So the auto complete would ideally block additional input if that input does not exist in the list.

Does something like that exist for the current jQuery UI / jQuery plugin? Or are there mods? I wish to use this method to speed up product selection, but not return a 'not found' page if someone types in something else.

Thank you in advance :)

Upvotes: 4

Views: 3415

Answers (2)

racl101
racl101

Reputation: 4100

Hi had a similar problem. Bud did not result to using the dropdown and or the combo box (which, is not fully supported) I decided to use the change event option for the autocomplete like so:

jQuery('#field').autocomplete ({
  ...
  source: listOfValues,   // assuming an array like this ['val1', 'val2', val3' ... ]
  change: function (event, ui) {
     // check if entered value exists
     var entered_valid_input = false;   // false until proven true
     jQuery.each(listOfValues, function(i,v) {
       if(jQuery('#field').val() == v) {
         entered_valid_input = true;
         return false;   // stop iterating
       }

     });
     if(!entered_valid_input) {
        // blank the field
        jQuery('#field').val("");
        return;    // exit callback. No further processing
     }

  },
  ...
  // further processing if the input is valid
});

Seems to work for me well. Even though it's not the most elegant solution.

Upvotes: 0

Robert Harvey
Robert Harvey

Reputation: 180777

This AutoComplete plugin has a function that allows you to test the value to make sure it is in the list.

Upvotes: 1

Related Questions