How to prevent form from submitting when within bo

2019-07-16 19:21发布

I'm experiencing an issue I hope anybody can clarify. I'm using bootstrap popover to trigger a login form. I would like to validate the user and password using ajax, but I'm not able to prevent the default submit event from the form event using preventDefault() and stopPropagation().

Find the code below just to see you can give me a hand and know what is going on. Thanks in advance.

Notes:

1) The popover trigger is the element with the id="signin_popover_trigger" 2) The popover content is the html code within the class="signin_popover_content"

HTML code:

<a href="javascript:void(0)" id="signin_popover_trigger" class="popover_trigger" data-name="signin" data-toggle="popover">Sign in</a>
<div class="signin_popover_content">
    <div class="signin_wrapper">
        <form class="user_access_form" method="post">
        <h4 class="blue weight-bold">Sign in</h4>
        <label class="grey weight-normal">Email:</label>
        <input type="text" name="user_email" class="form-control margin-bottom">
        <label class="grey weight-normal">Password:</label>
        <input type="password" name="password" class="form-control margin-bottom">
        <input type="submit" class="btn btn-info margin-top user_access_submit" name="sign_in_submit" value="Sign in">
        </form>
    </div>
</div>

Javascript code:

$('.user_access_form').submit(function(event){
    event.stopPropagation();
    event.preventDefault();
    //Validation code here
});


$('#signin_popover_trigger').popover({
    html: true,
    content: function(){
        return $('.signin_popover_content').html();
    },
    placement: 'bottom',

});

CSS code

.signin_popover_content {
    display: none;
}

The fact is that the form is stopped correctly if it's not put into the popover.

Thank you!!!

2条回答
萌系小妹纸
2楼-- · 2019-07-16 19:31

Expanding on my comment: what's happening is you're assigning the event handler, then creating the popup. When Boostrap creates the popup, it is removing the old form then creating a new form element in the DOM and so any previous event handlers are lost.

You can solve it by delegating the event:

$(document).on('submit', '.user_access_form', function(event){
    event.preventDefault();
});

Alternatively you could wait to assign the event handler, only after the popup is created.

查看更多
地球回转人心会变
3楼-- · 2019-07-16 19:56

I just discovered the answer. Bootstrap popover doesn't allow to add any event to the listener. The workaround would be the following:

$(document).on('submit', '.popover .user_access_form', function(event) {
     event.preventDefault();
     //Code here
});

Thanks MrCode for providing the answer. Cheers.

查看更多
登录 后发表回答