最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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

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.

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

Share Improve this question edited Mar 14, 2023 at 18:40 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked May 27, 2013 at 7:36 user1767586user1767586 4581 gold badge9 silver badges19 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

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');

});

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

try the following with jquery:

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

      alert('event');
});

Reference here.

发布评论

评论列表(0)

  1. 暂无评论