Run JavaScript on form submit in Drupal 7

6.8k Views Asked by At

I have a form with a few fields the user should fill out. The form also have two hidden fields for the users current position (lat, long). I have spent quite some time now trying to find a way to fill these fields.

How I want it to work is like this: When form is submitted (jQuery OR OnSubmit in form tag) a JavaScript function that asks the device for location should be run. The hidden fields is then filled with the result.

I have working code for doing this but I can't get it to be called by Drupal.

Is there any way to run a JavaScript function upon form submit in Drupal or should I find another way to do it.

Many thanks,

3

There are 3 best solutions below

1
Muhammad Reda On

Try to add onclick event to the submit button using #attributes.

$form['SUBMIT_BUTTON']['#attributes'] = array(
    'onclick' => array("YourJsCallback()"),
);

OR If you already have something inside ['#attributes'] array, so you will need to add to it.

$form['SUBMIT_BUTTON']['#attributes']['onclick'] = array("YourJsCallback()");
0
Fredrik Jonsson On

Seem to have got this to work now. Added the following

$form['#attributes'] = array('OnSubmit' => 'myFunction();');
0
Triss On

You have the following hook in "www/misc/ajax.js" that you can override in your javascript code:

/**
 * Modify form values prior to form submission.
*/
Drupal.ajax.prototype.beforeSubmit = function (form_values, element, options)
 {
      // This function is left empty to make it simple to override for modules
      // that wish to add functionality here.
 };