Reputation: 103
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
Reputation: 7177
Two things to watch out for:
_trackEvent
call triggered if the form passes validation.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
Reputation: 2491
You need a callback function that will fire both scripts on the single click event.
Upvotes: 1
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
Reputation: 419
I'm just guessing, but... What if you paste your code just before the return?
Upvotes: 1