Trigger a javascript event when an autocomplete field changes
Related to my fieldset summary problem: autocomplete fields do not trigger the change
event in Javascript, for some reason. I wound up stealing part of a patch I found somewhere (I would link to it if I could find it in my browser history) in order to override the autocomplete prototype function and trigger a new autocompleteSelect
event when the user chooses an item in an autocomplete field. Just drop this function into a Javascript file in your module or theme:
(function ($) {/** * Puts the currently highlighted suggestion into the autocomplete field. * Overridden from misc/autocomplete.js to add an event trigger on autocomplete */if (Drupal.jsAC) { Drupal.jsAC.prototype.select = function (node) { this.input.value = $(node).data('autocompleteValue'); // Custom: add an event trigger $(this.input).trigger('autocompleteSelect', [node]); };}})(jQuery);
Note that this goes inside the (function ($) {})(jQuery);
block that appears in most Drupal Javascript files. If you're pasting into an existing file that already has them, you can omit the first and last line, and paste the function in between them.
Then you just bind to that event. Here's an example for the node author field on the node add/edit form:
$('input[name=name]', context).bind('autocompleteSelect', function() { // Value chosen in autocomplete field. // Do whatever you need to do. var chosen_value = $(this).val();});
NOTE: After using this code for a few days I found an error. Drupal.jsAC
is not defined on all pages, so an error is thrown when trying to set values on the prototype of a non-existent object. I've updated the code above to wrap it in a condition to check for Drupal.jsAC
before overriding it.
One more update, from February 19, 2013:
It turns out that the select()
function only runs when you click on an item in the autocomplete dropdown. If you use the arrow keys to select and item and hit enter to select it, the hidePopup()
function runs instead (by way of onkeyup()
), so you need to implement that one to. This is the core version, with only the autocompleteSelect
trigger added:
Drupal.jsAC.prototype.hidePopup = function (keycode) { // Select item if the right key or mousebutton was pressed. if (this.selected && ((keycode && keycode != 46 && keycode != 8 && keycode != 27) || !keycode)) { this.input.value = $(this.selected).data('autocompleteValue'); // Custom: add an event trigger $(this.input).trigger('autocompleteSelect'); } // Hide popup. var popup = this.popup; if (popup) { this.popup = null; $(popup).fadeOut('fast', function () { $(popup).remove(); }); } this.selected = false; $(this.ariaLive).empty();};