2

Even the searching I have done that looks like there may be a solution doesn't really seem to answer this.

I have a form with an input value. When the user enters a value and clicks submit, I want to call a javascript routine and make that value available to it.

It seems simple enough, but I can't really find a good answer.

7

You need some jQuery on the page, e.g:

Drupal.behaviors.form_submit_processor = {
  attach: function (context, settings) {
    $("form#my-form").submit(function(e) {
      alert('form submitted');
      alert($('form#my-form #edit-name').val());
    });
  }
}

You could add to your theme script.js, with drupal_add_js or form_alter and $form['#attached'] ( recommended )

  • My form keeps redirecting to another URL. I changed the $form['#action'] value to url("#"). I'm not sure how to prevent Drupal from handling the submit and just let the JS handler deal with it. – vintorg Oct 6 '13 at 5:29
  • When I event.preventDefault() after my event handler, it seems to work. – vintorg Oct 6 '13 at 5:40
2

Alternatively you can do this from Form API where you have access to the form directly. This enables complex behaviours and form alterations on AJAX calls.

Take a look at the Ajax framework commands. You'll need to enable AJAX in your form too. Sometimes this is as simple as adding the no-js path argument in hook_menu or adding the use-ajax class on links. Read up on the AJAX framework in Drupal and ajaxifying forms.

After the hook_form_submit you can then return an array of commands to run including the roll-your-own ajax_command_invoke.

0

Here's how I did it:

Drupal.behaviors.form_submit_processor = {
  attach: function (context, settings) {

    // Function to be run before form submission
    var preFormSubmit = function () {
      // do some stuff here...
    }

    // Add a js function to run before form submission
    var formE = $('#my-form-id');
    formE
      .on('submit', function (e) {
        e.preventDefault();
        $.when(preFormSubmit()).done(function () {
          formE
            .off('submit')
            .submit();
        });
      });
    }
  };
})(jQuery);

Using $.when(preFormSubmit()).done allows preFormSubmit() to finish before the form is submitted.

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.