jQuery - prevent default, then continue default

后端 未结 10 1435
[愿得一人]
[愿得一人] 2020-12-02 16:27

I have a form that, when submitted, I need to do some additional processing before it should submit the form. I can prevent default form submission behavior, then do my addi

相关标签:
10条回答
  • 2020-12-02 16:56

    When you bind the .submit() event to the form, and you do the things you want to do before returning (true), these things happen prior to the actual submission.

    For example:

    $('form').submit(function(){
        alert('I do something before the actual submission');
        return true;
    });
    

    Simple example

    Another example on jquery.com: http://api.jquery.com/submit/#entry-examples

    0 讨论(0)
  • 2020-12-02 16:56

    This is, IMHO, the most generic and robust solution (if your actions are user-triggered, eg 'user clicks on a button'):

    • the first time a handler is called check WHO triggered it:
      • if a user tiggered it - do your stuff, and then trigger it again (if you want) - programmatically
      • otherwise - do nothing (= "continue default")

    As an example, note this elegant solution to adding "Are you sure?" popup to any button just by decorating a button with an attribute. We will conditionally continue default behavior if the user doesn't opt out.

    1. Let's add to every button that we want an "are you sure" popup a warning text:

    <button class="btn btn-success-outline float-right" type="submit"  ays_text="You will lose any unsaved changes... Do you want to continue?"                >Do something dangerous</button>
    

    2. Attach handlers to ALL such buttons:

    $('button[ays_text]').click(function (e, from) {
        if (from == null) {  // user clicked it!
            var btn = $(this);
            e.preventDefault();
            if (confirm() == true) {
                btn.trigger('click', ['your-app-name-here-or-anything-that-is-not-null']);
            }
        }
        // otherwise - do nothing, ie continue default
    });
    

    That's it.

    0 讨论(0)
  • 2020-12-02 16:58

    Using this way You will do a endless Loop on Your JS. to do a better way you can use the following

    var on_submit_function = function(evt){
        evt.preventDefault(); //The form wouln't be submitted Yet.
        (...yourcode...)
    
        $(this).off('submit', on_submit_function); //It will remove this handle and will submit the form again if it's all ok.
        $(this).submit();
    }
    
    $('form').on('submit', on_submit_function); //Registering on submit.
    

    I hope it helps! Thanks!

    0 讨论(0)
  • 2020-12-02 17:01

    You can use e.preventDefault() which will stop the current operation.

    than you can do$("#form").submit();

     $('#form').submit(function (e)
    {
        return !!e.submit;
    });
    if(blabla...)
    {...
    }
    else
    {
        $('#form').submit(
        {
            submit: true
        });
    }
    
    0 讨论(0)
提交回复
热议问题