How to add auto-complete support to textfield

In Drupal 7, it is pretty straightforward to add auto-complete support to any text field (much like the taxonomy fields).

hook_form_alter()

Place the following form_alter hook in your custom "mymodule".

function mymodule_form_alter((&$form, &$form_state, $form_id) {
  if ($form_id == "<id of form where autocompletion required>") {
     .
     .
     .

    // define the auto-completion values here
    // these will typically come from a data source
    $acValues = array("a", "b", "c", ... , 'z');

    $autocomplete['js'][] = array (
      'type' => 'setting',
      'data' => array('mymoduleACvalues' => $acValues)
    );
 
    $form["field_mytextfield"]["#attached"] = $autocomplete;
  }
}

jQuery behavior

Place the following jQuery behavior in some javascript file; either in the custom module or theme.

(function($) {
  Drupal.behaviors.mycustomAutoComplete = {
    attach : function(context, settings) {
      $(".field-name-field-mytextfield input").autocomplete({
        source : Drupal.settings.mymoduleACvalues
      });
    }
  }
})(jQuery);