Call a function with the submit button in HTML

回眸只為那壹抹淺笑 提交于 2021-02-20 03:56:06

问题


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>

回答1:


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



来源:https://stackoverflow.com/questions/52101029/call-a-function-with-the-submit-button-in-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!