0

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,

Muhammad Reda
  • 26,379
  • 14
  • 93
  • 105

3 Answers3

2

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()");
Muhammad Reda
  • 26,379
  • 14
  • 93
  • 105
  • Thanks! The problem is that it then only will work when someone clicks the button but not when hitting enter on the keyboard. The site is made to run on a mobile device but I cant take for granted that the users is not using external keyboard for their iPads. – Fredrik Jonsson May 15 '13 at 13:40
2

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

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

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.
 };
Triss
  • 96
  • 5