jquery: prevent default browser form submit behaviour but submit form with jquery?

北城余情 提交于 2019-12-01 11:30:57

问题


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


来源:https://stackoverflow.com/questions/5081674/jquery-prevent-default-browser-form-submit-behaviour-but-submit-form-with-jquer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!