Use submit event listener when form is submitted via inline JavaScript?

孤街浪徒 提交于 2019-12-24 10:53:41

问题


We have a script that tracks form submits by adding an event listener to the form. The problem is that one customer submits the form via a link using

<a href="javascript:document.formname.submit();">Submit</a>

which ignores the event listener. Here's a JSFiddle to demonstrate: http://jsfiddle.net/XhLkG/

As you can see the Submit button triggers the alert while the Submit link simply just submits the form and bypasses the event listener.

Is there a way to still trigger the event listener?

EDIT: We cannot change the markup since it's on our customer's homepage where they have embedded our script. Sorry if I didn't make it clear.


回答1:


You can use this:

var form = document.getElementsByClassName('form');
form[0].addEventListener("submit", function(e) {

    e.preventDefault();

    alert('event');

});
form[0].childNodes[3].addEventListener("click", function(e) {

    e.preventDefault();

    alert('event');

});



回答2:


try the following with jquery:

$("form").submit(function (e) {
      e.preventDefault();

      alert('event');
});

Reference here.




回答3:


instead of using the href try this

<form method="post" name="formname" class="form">
    <input type="text" name="hello">
    <a onclick="javascript:document.formname.submit();">Submit</a>
    <input type="submit">
</form>

remove the href and replace it with onclick



来源:https://stackoverflow.com/questions/16768433/use-submit-event-listener-when-form-is-submitted-via-inline-javascript

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