Reputation: 25
I'm trying to add a generic form onsubmit event listener to wide web site where i cannot add specific event listener to each and single pages.
The event should fire for all "form" element in the page.
What I've tried so far is:
$(function() {
$("form").submit(function(event) {
alert("submit");
});
});
Example page dom:
<form method="post">
<input type="text" name="afield" />
<button>
submit!
</button>
</form>
but the event does not fire, do you know what i'm doing wrong? I cannot edit the form html code, or create event handler targetting specific forms (e.g. by name/id).
Thank you!
Upvotes: 0
Views: 634
Reputation: 206048
Your form is getting submitted cause you need to event.preventDefault()
the default browser submit.
First make sure you've wrapped your code in DOM ready and
Use .on()
method with event delegation.
Use Event.preventDefault
jQuery(function( $ ){ // DOM is now ready and $ alias secured
$(document).on("submit", "form", function(event) { // Future and existent form Elements
event.preventDefault(); // prevent browser to default submit
alert("submit"); // do anything you like
});
});
https://api.jquery.com/ready/
http://api.jquery.com/on/
http://learn.jquery.com/using-jquery-core/document-ready/
https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault
Additionally make sure you've included the jQuery library and your <script>
tag (preferabily) right before the closing </body>
tag.
Upvotes: 2
Reputation: 74738
Add* a jQuery library before your script:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function() {
$("form").submit(function(event) {
alert("submit");
});
});
</script>
*: seems missing to me. Always have an eye on console for errors.
Upvotes: 1
Reputation: 21380
Your form seems to be appearing later, it doesn't exist from the begining.
$(function() {
$("body").on('submit', "form", function(event) {
alert("submit");
});
});
Upvotes: 1