Create auto-complete with ajax form in Drupal 7

Usually you can create auto-complete functionality in Drupal without facing any issue, the following example can help in creating a text field with auto-complete in drupal 7 :

here I will not discuss how to create auto-complete, it’s very easy thing but, here I want to point to an issue appears when you try to create auto-complete field in a form that submitted by ajax framework in drupal 7,¬† and try to make it more usable, the first thing to do for the filed is to make the result clickable and submit the form when the user click on the result item, and you accomplish this by overriding¬† function in misc/autocomplete.js = function (node) {
  this.input.value = $(node).data('autocompleteValue');

The first thing you will notice here after trying to test this is the page will refresh after the click on the result item, hmmm so what’s happening here is weird, but after some debugging and tracking the files and functions in the ajax framework in drupal 7, I noticed Drupal using ajaxForm plugin to submit the form so the form will be submitted after adding the above override to the website, so to make it work with the ajax framework this need some modification so we can click on the auto-complete result item and submit the form by ajax, so here is the modification I added to the code above to make it work with the ajax framework : = function (node) {
  this.input.value = $(node).data('autocompleteValue');
  if(jQuery(this.input.form).hasClass('ajax-processed')) {
    var options = {
      dataType : 'script',
      url : Drupal.settings.basePath + 'system/ajax',
      type : 'POST',
      data : {_triggering_element_name : "op", _triggering_element_value : ''}
  } else {
  //return false to prevent normal browser submit and page navigation
  return false;

2 thoughts on “Create auto-complete with ajax form in Drupal 7

  1. web hosting says:

    Exactly what I was searching for, thanks for putting up. cheap cpanel hosting | web hosting |

  2. Zsolt says:

    Please check before implementing the first option and reaching an infinite loop.

Leave a Reply

Your email address will not be published. Required fields are marked *