简体   繁体   中英

Call a function with the submit button in HTML

I need a Google AdWords conversion script to work whenever someone submits a form for a free quote. Google has provided the script which I'm put into a Snippet with WordPress and activated it for the site.

I now need to call that function when the submit button is pressed, but I can't remember the correct syntax and Google searches so far have led me down long paths of .php file creations that isn't answering what feels like a simple solution would solve.

Currently I have added the function in line with the existing code for the submit, but I'm not convinced this is correct. The below code is on the contact form that the page uses.

[submit id:submit class:btn class:btn-primary gtag_report_conversion() "Send"]

Below is the code I put into the Snippet minus the full "send to" AW address:

<script>
function gtag_report_conversion(url) {
  var callback = function () {
    if (typeof(url) != 'undefined') {
      window.location = url;
    }
  };
  gtag('event', 'conversion', {
      'send_to': 'AW-.....',
      'event_callback': callback
  });
  return false;
}
</script>

Depending on how that shortcode was implemented, odds are you can't just add inline event handlers to it like that - and without seeing the source code it's hard to determine (but I'd wager that it's most likely the case).

Just add this in the old fashioned way with the onclick or onsubmit event handler. I'd recommend the onsubmit since forms can be submitted without clicking on the button.

Since you've already loaded in your Script, you can just add to it:

<script>
    function gtag_report_conversion(url){
        var callback = function () {
            if (typeof(url) != 'undefined') {
                window.location = url;
            }
        };
        gtag('event', 'conversion', {
                'send_to': 'AW-.....',
                'event_callback': callback
        });
        return false;
    }

    document.getElementById("your-form-id").onsubmit = function(){
        gtag_report_conversion();
    };
</script>

Just replace your-form-id with the id of your <form> element (not your submit button).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM