user1016078
user1016078

Reputation: 103

Two onclick functions in one submit button

I would like to add Google Analytics track event code to a submit button using the onclick function, however there is already a onclick function there.

Existing code

<input name="Submit" type="submit" class="button" style="float:left; clear:both;" onclick="MM_validateForm('name','','R','contact_number','','R','email','','RisEmail','address1','','R','address2','','R');return document.MM_returnValue" value="Submit" />

Code I want to add

onclick="_gaq.push(['_trackEvent', 'Contact Page Enquiry', 'Enquiry', 'Contact Page Enquiry']);"

Can this be done?

Upvotes: 1

Views: 4818

Answers (4)

mike
mike

Reputation: 7177

Two things to watch out for:

  1. You probably only want the _trackEvent call triggered if the form passes validation.
  2. Event tracking works by requesting a tracking pixel from an analytics server. If the form submission causes loading a new page to the same window before the tracking request has completed, you can end up with missing or partial data collection.

You can get around the second issue by delaying the form submission.

<input id="Submit" name="Submit" type="submit" ... />
...
$('#Submit').click(function(e) {
  // Prevent the default handling of the form submit button
  e.preventDefault();
  MM_validateForm('name', ...
  // If the form didn't validate, don't do anything else
  if (!document.MM_returnValue) return;
  _gaq.push(['_trackEvent', ...
  // Get the form & submit it after 150ms delay
  var form = $(this).parents('form:first');
  setTimeout(function() {form.submit()},150);
});

Upvotes: 0

Alex Gill
Alex Gill

Reputation: 2491

You need a callback function that will fire both scripts on the single click event.

http://jsfiddle.net/gF7Td/2/

Upvotes: 1

bhb
bhb

Reputation: 2561

If you are using a jQuery it works. You can have multiple onclick event on a single element.

Check this

Code

document.getElementById("a").onclick = function() {
   alert(2); //this over writes the onclick on the element. This is called
};

$("#a").click(function() {
    alert(3); //this is called
});​

HTML:

<a id="a" onclick="alert(1)">click</a>​

Check other SO questions like this or this

From the links above you can do something like this:

<input name="Submit" type="submit" class="button" style="float:left; clear:both;" onclick="MM_validateForm('name','','R','contact_number','','R','email','','RisEmail','address1','','R','address2','','R'); _gaq.push(['_trackEvent', 'Contact Page Enquiry', 'Enquiry', 'Contact Page Enquiry']); return document.MM_returnValue" value="Submit" />

This is untested by the way.

Upvotes: 1

Armaggedon
Armaggedon

Reputation: 419

I'm just guessing, but... What if you paste your code just before the return?

Upvotes: 1

Related Questions