How to programmatically trigger a click on an AJAX enabled form submit button?

I'm trying to programmatically (with jQuery) trigger a click on button with AJAX behavior in a Drupal form, but so far jQuery('#edit-submit').click() doesn't do anything.

A real mouse click on that button works as intended. Any ideas how to make it work?

Answers 7


  • Actually, there's no need to guess.

    You should use Drupal behaviors

    Drupal.behaviors.yourFunctionName = {
        attach:function (context, settings) {
    
           // Your code goes here....
    
        }
    }
    

    This will give you access to the settings' ajax property,

    Drupal.behaviors.yourFunctionName = {
        attach:function (context, settings) {
    
           console.log(settings.ajax);
    
        }
    }
    

    Depending on your configuration, you should see a list of triggering elements, with various properties such as the name of the callback function, the selector's id as well as the name of the triggering event.

    You can then use the relevant information to trigger your event.

    // $(selector).trigger(eventName);
    // for example...
    $('#edit-product-id-15', context ).trigger('change');
    

  • Create ajax submit like the following.

     $form['button'] = array(
        '#type' => 'button',
        '#value' => 'Click',
        '#ajax' => array(
          'callback' => '_kf_reading_user_points',
          'wrapper' => 'reading-user-points',
          'method' => 'replace',
          'event' => 'click',
        ),
      );
    
    function _kf_reading_user_points(&$form, &$form_state) {
      // Something within the callback function.
    }
    

    Then the jquery .click() event would be work in the drupal ajax form.



  • In my case, the above recommended solutions didn't work for me, but the mention of .mousedown() led to the following idea that worked for me (Drupal 7):

    $('#custom-submit-button').click(function() {
      $('#ajax-submit-button').trigger('mousedown');
    });
    

    There's some helpful background info about "why" this is the case in the Form API Reference under #ajax_prevent


  • Looking at the Better Exposed Filters module, they submit the AJAX form by finding $(.ctools-auto-submit-click') and trigging a click.

    <?php
    // ... near line 190 of better_exposed_filters.js
    
    // Click the auto submit button.
    $(this).parents('form').find('.ctools-auto-submit-click').click();
    ?>
    


Related Questions