5

In Drupal 7, when you are within an autocomplete field on a node edit form (in my case, it is specifically an entity reference autocomplete field), pressing the Enter key submits the entire form.

How do I disable this behavior?

  • 1
    drupal.org/node/1931180 – arpitr Oct 1 '13 at 23:45
  • I've done some testing on simplytest.me and confirmed that this happens on a bare install, on many types of fields. For now, I've created a module which completely disables the enter key via JS--obviously not ideal. – ouni Oct 2 '13 at 14:17
  • 1
    hey why don't you open an issue queue on drupaal.org – arpitr Oct 2 '13 at 14:26
3

Here's a nice solution that will allow the user to press Enter in order to select an autocomplete option.

<script>
(function($) {

Drupal.behaviors.ACChangeEnterBehavior = {
  attach: function(context, settings) {
    $('input.form-autocomplete', context).once('ac-change-enter-behavior', function() {
      $(this).keypress(function(e) {
        var ac = $('#autocomplete');
        if (e.keyCode == 13 && typeof ac[0] != 'undefined') {
          e.preventDefault();
          var fauxEvent = $.Event('mousedown'); // Create an event to trigger
          $('li.selected', ac).trigger(fauxEvent);
        }
      });
    });
  }
}

})(jQuery);
</script>

Note: This will only override the behavior of Enter while the autocomplete dropdown is visible. Otherwise, pressing Enter does the normal behavior (submits the form).

But if you want to halt form submission via Enter in any input field, try the following:

<script>
(function($) {

Drupal.behaviors.DisableInputEnter = {
  attach: function(context, settings) {
    $('input', context).once('disable-input-enter', function() {
      $(this).keypress(function(e) {
        if (e.keyCode == 13) {
          e.preventDefault();
        }
      });
    });
  }
}

})(jQuery);
</script>
  • 1
    Thank you for both examples, they did help me! Only one comment: a closing } is missing right before the last line of code: )(jQuery); – Marcos Buarque Feb 17 '14 at 2:59
1

A slightly more concise version of answer #2 (the faux event is not needed).

<script>
!(function ($) {
  'use strict';
  Drupal.behaviors.ACChangeEnterBehavior = {
    attach: function (context, settings) {

      // Prevent the autocomplete from triggering the submit event.
      $('input.form-autocomplete', context).once('ac-change-enter-behavior').keypress(function (e) {
        if (e.keyCode === 13 && this !== undefined) {
          e.preventDefault();
        }
      });

    }
  };
}(jQuery));
</script>
0

Pressing enter in many fields would trigger the form submit. The only way you can disable this behavior is by custom JS, as you've done.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.