KleberBH
KleberBH

Reputation: 462

Jquery to stop click event until function is completed

I have a button that when it is clicked triggers this:

var approved = false;

$('.confirm').on('click', function (e) {
    var type = $(this).attr("data-confirm");
    if (approved === false) {
        bootbox.confirm("Are you sure would like to " + type +"?", function (result) {
            if (result) {
                approved = true;
                $(this).trigger('click');
            }
        });
        e.preventDefault();
    }
});

Its a modal confirm box with 2 buttons, cancel and confirm. The goal here is to wait the click to perform until the user clicks on confirm box. When the code runs it display the box and wait, if user clicks cancel, its close the modal and don't trigger the clicks, perfect fine, if the user clicks on confirm it closes the modal, assign approved to true, however the click event doesn't trigger again with new command.

how can I change this to perform this.

if approved is false, load bootbox.confirm and pause. User clicks confirm its loads if(result) assign approved to true and continue the click.

Any help? thanks

Upvotes: 1

Views: 2884

Answers (2)

KleberBH
KleberBH

Reputation: 462

Ok

I found the solution, hope it could help somebody else. Here is my solution:

HTML

<button type="button" class="btn btn-primary mybutton" data-confirm="submit"> Submit</button>

JS

$('.mybutton').on('click', function (e) {
    var type = $(this).attr("data-confirm"),
    bootbox.confirm("Are you sure would like to " + type + "?", function (result) {
        if (result) {
           $('#Myform').submit();
        }
        else {
           e.eventPrevent();
        }
    });
});

Basically what I did was to change the button type from submit to button. Then on button click, it checks the confirm, if user click yes it submit the form, else it prevent the click to continue.

Works nice now.

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

I problem that is there is this inside the click handler is not the same as the clicked button

var approved = false;

$('.confirm').on('click', function (e) {
    var type = $(this).attr("data-confirm"),
        //use a closure variable since `this` inside the confirm callback is not the button
        $this = $(this);
    if (approved === false) {
        bootbox.confirm("Are you sure would like to " + type + "?", function (result) {
            if (result) {
                approved = true;
                $this.trigger('click');
            }
        });
        e.preventDefault();
    }
});

Note: This still may not work in all cases. ie if the original click had an default action like anchor element click that may not trigger, also if there is another click handler registered that may will get still triggered.

Upvotes: 1

Related Questions