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 badges3 Answers
Reset to default 2You 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.