简体   繁体   中英

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 (eg by name/id).

Thank you!

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.

Your form seems to be appearing later, it doesn't exist from the begining.

$(function() {
    $("body").on('submit', "form", function(event) {
        alert("submit");
    });
});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM