jquery: prevent default browser form submit behavi

2019-02-20 06:58发布

问题:

$('#search_form').submit(function(e) {
    //e.preventDefault();
    return false;
})

This works just fine to prevent form submission when pressing Enter.

However even I have this I want to submit the form with jquery if certain circumstances are true.

edit:

$('#search_form').submit(function(e) {
    return !!e.submit;
});

function ...

    if (e.keyCode == 13) {

        if (blablabla) {

            ... // do something

        } else {
            $('#search_form').submit({submit:true}); //doesn't work
            console.log('submitted'); //this does successfully get fired
        }

    }

If I press enter the form doesn't get submitted, but the log in in the console happens!

回答1:

$('#search_form').submit(function(e) {
   if($('.errors').is(':visible')){
        e.preventDefault();
        // do something else here// some errors are visible :)
        return false; 
   }else{

   }
})


回答2:

By checking the type of e.originalEvent we can determine if human (type object) or script (type undefined) submitted the form:

$('#search_form').submit(function(e) {
    if (typeof e.originalEvent !== 'undefined') {
        e.preventDefault();
    }
})

Invoke a jquery trigger to submit the form:

$('#search_form').trigger('submit');