jquery: prevent default browser form submit behavi

2019-02-20 06:48发布

$('#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!

2条回答
倾城 Initia
2楼-- · 2019-02-20 06:55

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');
查看更多
爷、活的狠高调
3楼-- · 2019-02-20 07:07
$('#search_form').submit(function(e) {
   if($('.errors').is(':visible')){
        e.preventDefault();
        // do something else here// some errors are visible :)
        return false; 
   }else{

   }
})
查看更多
登录 后发表回答