Wayward Semicolon
Wayward Semicolon

Reputation: 9

Event listener for form submit in javascript with NO submit action

I have been building a chrome extension and I have been using content scripts to listen for the form submit event. I was testing my extension and it works pretty well, until I tested on a site that didn't work. The reason it didn't work is because the form button isn't really a form button with the submit action. It's actually an <a> tag with an href tag that links to "javascript:;", so the submit event doesn't trigger. The link is inside a form, it's just not a button tag with the submit action. How can I make sure that my content script triggers whenever a user tries to submit a form?

Upvotes: 0

Views: 2514

Answers (1)

Schlaus
Schlaus

Reputation: 19212

It seems simple at a glance, but there's no surefire way to achieve what you're asking.

Consider this:

document.getElementById('myform').addEventListener('submit', function(e) {
  e.preventDefault();
  console.log(document.getElementById('sometext').value);
  console.log('form submitted');
});

document.getElementById('notasubmitbutton').addEventListener('click', function(e) {
  console.log(document.getElementById('sometext').value);
});
<form id="myform">
  <input type="text" id="sometext">
  <input type="submit">
  <button id="notasubmitbutton" type="button">Submit 2</button>
</form>

There's the regular submit button that will trigger the submit event. Then there's another button, that will just collect all the data from the form, but will not submit it in the traditional sense.

There's absolutely no way you could foresee all the possible ways someone could build their form, so what you're asking for can't be done.

Upvotes: 1

Related Questions