user8463989
user8463989

Reputation: 2459

cannot stop bootstrap modal from closing on button click after failed validation

I know this question has been asked a few times but using e.preventDefault() or event.preventDefault() did not seem to work for me.

This is the code snippet:

$(".save").on("click", function (e) {
     e.preventDefault();
    var noImages = $('input[name="pics[]"]:checked').length;
        if(noImages > 1) {
            alert("Only one image allowed");
        } else {
        // allow selection and close modal

If more than one image is selected in the modal, it alerts the message but closes the modal which it shouldn't. The modal should only close if the user selects one image and then clicks on "save".

<button type="button" class="btn btn-primary save" data-dismiss="modal">Save</button>

Upvotes: 0

Views: 514

Answers (1)

arbuthnott
arbuthnott

Reputation: 3819

If you want to control the closing of your modal, you should remove data-dismiss="modal" from your html. The issue then will be triggering the close when you want to.

Bootstrap gives a handle for this with .modal('hide'). For example, in your save click handler:

$(".save").on("click", function (e) {
    e.preventDefault();
    var noImages = $('input[name="pics[]"]:checked').length;
    if(noImages > 1) {
        alert("Only one image allowed");
    } else {
        $(e.target).closest('.modal-dialog').modal('hide');
    }
});

If you modal has an id, you can also find it that way instead of closest.

Upvotes: 1

Related Questions