1. Germano Gabbianelli
  2. django-autocomplete
  3. Issues
Issue #14 new

jquery ui autocomplete initial value bug

benkraft
created an issue

jquery_autocomplete.js has issues if used with initial (or manually set) values.

The code, {{{

!javascript

this.select = function (event, ui) { 65 // set the hidden input field. 66 this.last_item = ui.item; 67 this.hidden_input.val(ui.item.id); 68 }; 69 70 this.close = function (event, ui) { 71 alert(ui.toSource());
72 }; 73 74 this.setup = function () { 75 this.input = $("#id_" + this.name); 76 this.hidden_input = $("#id_hidden_" + this.name); 77 this.last_item = {}; 78 this.input.autocomplete({ 79 // minLength: 2, 80 source: jQuery.proxy(this.source, this), 81 select: jQuery.proxy(this.select, this), 82 }); 83 this.input.closest("form").submit(jQuery.proxy(function () { 84 if ((!this.input.val()) || (this.hidden_input.val() != this.input.val() 85 && !this.force_selection)) { 86 this.hidden_input.val(this.input.val()); 87 } 88 }, this)); 89 if (this.force_selection) { 90 this.input.focusout(jQuery.proxy(function (event) { 91 if (this.input.val() != this.last_item.value) 92 this.input.val(""); 93 }, this)); 94 } 95 };

}}}

relies on this.last_item being set. It's not set if you have an initial value or set the widget manually, so the box will clear when it loses focus on these values (if you tab through them, etc).

A better solution is to use the this.change event to clear invalid values, {{{

!javascript

this.change = function (event, ui) { 75 if (this.force_selection){ 76 if (!ui.item) { 77 // remove invalid value, as it didn't match anything 78 this.input.val(""); 79 this.hidden_input.val(""); 80 return false; 81 } 82 }
83 return true;
84 85 }; 86 74 87 this.setup = function () { 75 88 this.input = $("#id_" + this.name); 76 89 this.hidden_input = $("#id_hidden_" + this.name); … … @@ -80,21 +93,11 @@ function jquery_autocomplete(name, ac_ur 80 93 // minLength: 2, 81 94 source: jQuery.proxy(this.source, this), 82 95 select: jQuery.proxy(this.select, this), 96 change: jQuery.proxy(this.change, this), 83 97 // always select first 84 98 selectFirst: true 85 99 });

}}}

It also seems the event on submit wrecks havoc if force_selection is not used.

Comments (1)

  1. Log in to comment