1

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user1767586
  • 438
  • 1
  • 8
  • 19

3 Answers3

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

});
veelen
  • 1,916
  • 19
  • 26
0

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

ianace
  • 1,646
  • 2
  • 17
  • 31
  • Thanks but I have no control over the link. The customer has embedded our script on their homepage. – user1767586 May 27 '13 at 07:44
  • 2
    hrefs should not be removed from anchors, it causes them not to function properly and it also breaks the browser default stylings. use either href="#" (it will take you to the top of the page) or href="javascript:void(0)" (best option) – Ted May 27 '13 at 08:12
0

try the following with jquery:

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

      alert('event');
});

Reference here.

Ted
  • 3,985
  • 1
  • 20
  • 33