Arun Arun - 4 years ago 165
Javascript Question

JQuery custom confirm box callback error

In my project I am using a custom

Confirmation dialogue
, which uses the
callback
method of
JQuery
.

Custom Function is

function conf_close() {
$('.conf-cont-main').remove();
}
function confirmMsg(message, callback)
{
$('.conf-main').remove();
var cont = '<div class="conf-cont-main"><div class="conf-main">\n\
<span class="conf-close" onclick="conf_close()">X</span>\n\
<div class="conf-head">\n\
Confirm Action\n\
</div>\n\
<div class="conf-body">\n\
' + message + '\n\
</div>\n\
<div class="conf-button">\n\
<button class="btn btn-blue-3 btn-sm btn-flat" id="conf-yes">Yes</button>\n\
<button class="btn btn-blue-3 btn-sm btn-flat" id="conf-no">No</button>\n\
</div>\n\
</div></div>';
$('body').prepend(cont);
$(document).on('click', '#conf-yes', function()
{
callback(true);
});
$(document).on('click', '#conf-no', function()
{
callback(false);
});
}


I am calling this function as

var c = confirmMsg('Are You Sure to Delete?', function(c) {
if (c == true) {
alert('true');
conf_close();
//ajax call
}
else{
alert('false');
conf_close();
}
});


The issue is, when i call
confirmMsg()
for the first time, it works as expected and alrt() will show once. When I call
confirmMsg()
for secondtime. it show alert 2 times and so on.


How can I resolve this issue?
Any help could be appreciated.
The example fiddle link is JSFiddle

Answer Source

It's because of these lines of code:

$(document).on('click', '#conf-yes', function()
{
    callback(true);
});
$(document).on('click', '#conf-no', function()
{
    callback(false);
});

You are adding the events each time its called, so they run multiple times. Try changing to this:

$('#conf-yes').off('click');
$('#conf-no').off('click');
$(document).on('click', '#conf-yes', function()
{
    callback(true);
});
$(document).on('click', '#conf-no', function()
{
    callback(false);
});

While it would probably be smarter to set up your JS so it only adds the event once (presumably outside of the time of call to that function), the .off() will remove the previous click events so when you add them again you won't have duplicates.

But if you want to move forward with that code, you could also shorten it a bit:

$('#conf-yes').off('click').on('click', function()
{
    callback(true);
});
$('#conf-no').off('click').on('click', function()
{
    callback(false);
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download