Solution for restricting input values to the source returned by autocomplete
I spent most of my day trying to implement input "validation" on a field employing the jquery ui autocomplete feature. I'm not experienced enough with javascript to truly understand how terrible I am at it, so please be kind.
Problem: The out of the box autocomplete examples allow users to enter anything they want into the autocompleted field.
Ideal Behavior: If, upon field exit, the value left in the field does not match what any of the items returned by the source property, clear the field and any associated inputs.
Solution: Assign logic to change event that runs the field's current value against the cached source items
- /*
- * Setup autocomplete on field value input
- *
- * caches values for validation
- */
- var $cache = {};
- $('input#code_dsp').autocomplete({
- source: function(request, response) {
- $.ajax({
- url: $('input#code_dsp').attr('data-href'),
- data: {
- field: $('select#field').val(),
- search: request.term
- },
- type: "POST",
- dataType: "json",
- success: function(data) {
- // cache data for use in change event
- $cache = data;
- // returned data has value in "val" property
- // and label in "label" and "value" property
- response(data);
- }
- })
- },
- minLength: 2,
- select: function(event, ui) {
- // preferred to have actual value in hidden
- // field and leave label in main field
- $('input#code').val(ui.item.val);
- },
- change: function(event, ui) {
- // assume we don't have a match
- var $match = false;
- // for each row of objects in json object
- for (var $row in $cache)
- {
- // is current value match to label in row?
- if (this.value == $cache[$row].label)
- {
- // found a match, input is validated!
- $match = true;
- console.log('Found match: '+$cache[$row].label);
- }
- }
-
- if ($match == false)
- {
- // uh-ohs. No match, so clear both input#code_dsp
- // and the corresponding hidden input#code field
- console.log('No match. Clearing input values');
- this.value = '';
- $('input#code').val('');
- }
-
- },
- focus: function(event, ui) {
- // found this in another forum post
- // keeps the mouse-over event from dropping
- // the "hovered" item into the autocompleted
- // field.
- return false;
- }
- });
It seems to work well in my app. Hope this helps someone. By the way, I'm using jquery 1.4.2 and jquery-ui 1.8.