jQuery: Trigger submit on ajax enabled form in Drupal

Published by Lennart Van Vaerenbergh on April 22, 2015

I was trying to trigger 'click' on an ajax enabled submit button when hitting Enter in a text field. Well that was a disappointment. Fear not, there's a solution. Just keep in mind that click() or trigger('click') is not going to work for us to fire off the form submit.

Drupal Form API way

Add the highlighted line to your textfield in the form array:
$form['element'] = array(
  '#type' => 'textfield',
  '#title' => 'Title',
  '#ajax' => array(
    'callback' => '...',
    'keypress' => TRUE,

Non Drupal Form API way

First of all, in our javascript file, let's create a function that provides us with an onEnter event. By default, your 'hit enter and submit' won't work on your ajax enabled form, so we'll define the 'hit enter' trigger ourselves.
$.fn.onEnter = function(func) {
  this.bind('keypress', function(e) {
    if (e.keyCode == 13) func.apply(this, [e]);    

  return this; 
Source: http://stackoverflow.com/a/6524616

Second and last step, we'll add the trigger to our input text field and instead of using click() or trigger('click'), we'll use mousedown().
$('input#form-text-field').onEnter(function() {

That's it. Your form should be submitting when hitting enter from within the text field.

The explanation about the why can be found on the Ajax Framework page on Drupal.org. Here's a quote:
When binding #ajax behaviors to form buttons, pressing the ENTER key within a textfield triggers the 'click' event of the form's first submit button. Triggering Ajax in this situation leads to problems, like breaking autocomplete textfields. Because of that, Ajax behaviors are bound to the 'mousedown' event on form buttons by default. However, binding to 'mousedown' rather than 'click' means that it is possible to trigger a click by pressing the mouse, holding the mouse button down until the Ajax request is complete and the button is re-enabled, and then releasing the mouse button. For this case, 'prevent' can be set to 'click', so an additional event handler is bound to prevent such a click from triggering a non-Ajax form submission. This also prevents a textfield's ENTER press triggering a button's non-Ajax form submission behavior.
Source: https://api.drupal.org/api/drupal/includes%21ajax.inc/group/ajax/7


Submitted by Rapsan jani on Sunday, April 12, 2020 - 08:44
Greate tutorials. I have found another article to <a href="https://bit.ly/2K0dYj0"> trigger click button on pressing enter</a>

Add new comment

(If you're a human, don't change the following field)
Your first name.
(If you're a human, don't change the following field)
Your first name.
This challenge is for testing whether or not you are a human visitor and to prevent automated spam submissions.