0

I am using JavaScript to validate form fields. If it passes I want to send an event to Google analytics. However it isn't sending the event to GA. In my form I have:

<form role="form" name="submit" method="post" onSubmit="return validateForm();">

And my validation code is:

function validateForm() {    
// validate the form and update the section if there is an error
var spamCheck = document.submit.inputSpamCheck.value;
    if( document.submit.inputName.value == '' ){
        document.submit.inputName.focus();
        $( "#name-section" ).addClass( "has-error" );
        return false;
    }
    else if( document.submit.inputEmail.value == '' ){
        document.submit.inputEmail.focus();
        $( "#email-section" ).addClass( "has-error" );
        return false;
    }
    else if( document.submit.inputSpam.value != spamCheck ){
        document.submit.inputSpam.focus();
        $( "#spam-section" ).addClass( "has-error" );
        return false;
    }
    else{       
        _gaq.push(['_trackEvent', 'Form', 'Submitted', 'successful', 5]); 
        return true;
    }
}
  • So, you don't control the target page and can not put the tracking there? – pawel Sep 24 '13 at 18:49
  • 1
    Also http://stackoverflow.com/questions/4086587/track-event-in-google-analytics-upon-clicking-form-submit (look at the top-voted, not just the accepted answer) – pawel Sep 24 '13 at 18:51
  • The page updates it's self on successful form completion, so there is no target page. I actually removed the submit function from the form and rewrote the JavaScript to do the validation and submission in JQuery without reloading the page. It turned out the POST command was blowing away the GA push. – FreshClicks Sep 24 '13 at 21:28
  • But after the self-update you should know if there was posted data and if it was valid, so you could print a ` – pawel Sep 25 '13 at 08:06

1 Answers1

0

I that this is an old question but I would love to answered just in case someone needs helps.

The onsubmit="" form event would do if you paste the following script in the <head> section of the form page like this

<script language="javascript">
    function checkContVal()
    {
        var fun = document.submit;
        if(fun.name.value == ""){
            //do something
            return false;
        }
        if(fun.email.value == ""){
            //do something
            return false;
        }
        if(f.securityCode.value == ""){
            //do something
            return false;
        }
    _gaq.push(['_trackEvent', 'Form', 'Submitted', 'successful', 5]); 
    //ga('send', 'event', 'Category','Submit','Contact Us page enquiry'); OR this event if using universal GA.
    return true;
    }
</script>  
Raul Reyes
  • 453
  • 1
  • 4
  • 12