Using JQuery - preventing form from submitting

后端 未结 13 2640
灰色年华
灰色年华 2020-11-22 06:51

How do I prevent a form from submitting using jquery?

I tried everything - see 3 different options I tried below, but it all won\'t work:

    $(docu         


        
相关标签:
13条回答
  • 2020-11-22 07:07

    You forget the form id, and it works

    $('form#form').submit(function(e){
       e.preventDefault();
       alert('prevent submit');             
    });
    
    0 讨论(0)
  • 2020-11-22 07:09

    I also had the same problem. I also had tried what you had tried. Then I change my method not to use jquery but by using "onsubmit" attribute in the form tag.

    <form onsubmit="thefunction(); return false;"> 
    

    It works.

    But, when I tried to put the false return value only in "thefunction()", it doesn't prevent the submitting process, so I must put "return false;" in onsubmit attribute. So, I conclude that my form application cannot get the return value from Javascript function. I don't have any idea about it.

    0 讨论(0)
  • 2020-11-22 07:09

    Using jQuery, you can do the following:

    1- Use the native form submit event with a Submit button, while preventing the event from firing, then

    2- Check the form Valid property This can be implemented as following:

    1- HTML:

     <form id="yourForm">
        <input id="submit" type="submit" value="Save"/>
    </form>
    

    2- Javascript

     $("form").on("submit", function (e) {
            e.preventDefault();
            if ($(this).valid()) {  
               alert('Success!');
            }
        });
    
    0 讨论(0)
  • 2020-11-22 07:13

    This also appears to work and may be slightly simpler:

    $('#Form').on('submit',function(){
        return false;
    })
    
    0 讨论(0)
  • 2020-11-22 07:14

    Attach the event to the submit element not to the form element. For example in your html do like this

    $('input[type=submit]').on('click', function(e) {
        e.preventDefault();
    });
    
    0 讨论(0)
  • 2020-11-22 07:17
    // Prevent form submission
    $( "form" ).submit(function( event ) {
      event.preventDefault();
    });
    

    from here: https://api.jquery.com/submit-selector/ (interesting page on submit types)

    0 讨论(0)
提交回复
热议问题