Stefano
Stefano

Reputation: 25

jQuery event submit not firing on user action

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

Answers (3)

Roko C. Buljan
Roko C. Buljan

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

Jai
Jai

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

Qwertiy
Qwertiy

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

Related Questions