简体   繁体   中英

Run JavaScript on form submit in Drupal 7

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,

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()");

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

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

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.
 };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM