Jason Jason - 1 month ago 10
Javascript Question

Button incrementing and firing multiple times on click

So I have a web app that I'm working on, and I have a section of the app that has a deploy button, which launches a modal. In the modal, I have two more buttons, one to confirm and one to cancel.

When the modal launches and I click one of the buttons, it fires once. However, my problem is that if I exit out of the modal, reopen it and click a button again, it will trigger the button twice. This continues if I repeat the process, so the next click would trigger three clicks and so on and so forth.

I've tried using

unbind
and
one
to no avail in jQuery and am kind of stumped at this point.

Here is the relevant jQuery for that section. I can also attach the handlebars file I'm using if that would help.

jQuery:

//open modal, present OK and Cancel buttons
$(".inventory").on('click', 'button.deploy', function () {
console.log('DEPLOY')
var machine = $(this).data("machine");
var message = "Are you <b>SURE</b> you want to deploy the following machine:\n\n<b>" + $(this).data("machine") + "</b>";
var newNetwork = $(this).parent().siblings(".select-option").find("option:selected").val();
var currentDefault = $(this).parent().siblings(".select-option").attr('defaultValue');
if (currentDefault !== newNetwork) {
message += "\n\nChanging the network from: \n\n " + currentDefault + " -> <b>" + newNetwork + "</b>\n\n";
}
else {
message += "\n\nRestarting with the network:\n\n<b>" + currentDefault + "</b>\n\n";
}
message += "<i>NOTE: Any other network changes made to other machines will result in possible changes "
message += "the next time there is a full deploy.</i>"

$("#reset-message").html(message);
$(".jquery-modal.blocker.current").show();
$("div #reset-modal.modal").show();

$("div #reset-modal").on('click', "#deploy-cancel", function () {
$(".jquery-modal.blocker.current").hide();
$("div #reset-modal.modal").hide();
console.log('CANCEL')
});

$("div #reset-modal").on('click', "#deploy-confirm", function () {
$(".jquery-modal.blocker.current").hide();
$("div #reset-modal.modal").hide();
console.log('CONFIRM')
});

Answer

It seems like you are adding multiple event handlers.

Try this:

   $("div #reset-modal").off('click', "#deploy-cancel").on('click', "#deploy-cancel", function ()        {
        $(".jquery-modal.blocker.current").hide();
        $("div #reset-modal.modal").hide();
        console.log('CANCEL')
    });

    $("div #reset-modal").off('click', "#deploy-confirm").on('click', "#deploy-confirm", function () {
        $(".jquery-modal.blocker.current").hide();
        $("div #reset-modal.modal").hide();
        console.log('CONFIRM')
     });
Comments