表单验证和Google Analytics事件跟踪

时间:2013-09-24 18:46:21

标签: javascript jquery google-analytics

我使用JavaScript来验证表单字段。如果它通过我想发送一个事件到谷歌分析。但是它没有将事件发送给GA。在我的表格中,我有:

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

我的验证码是:

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

1 个答案:

答案 0 :(得分:0)

我认为这是一个老问题,但我希望能够回答以防万一有人需要帮助。

如果您将以下脚本粘贴到表单页面的<head>部分,就会执行onsubmit =“”表单事件

<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>