javascriptjqueryjqxwidgets

Why does my dynamically confirm box only work once?


I have attempted to create a custom confirm UI dialog box, which works perfectly on the 1st attempt, and then on a second attempt of running it, I no longer get alerted of my choice as well as the window does not close. Why is that? What else am I doing wrong here that I perhaps overlooked?

Here is the HTML and Javascript in question:

<input type="button" id="Button" value="Click Me" />

$('#Button').click(function () {
    confirmUI('is OK?', 'confirm', function () {
        alert('click OK');
    }, function () {
        alert('click Cancel');
    });
});


var confirmUI = function (text, title, callbackOkClose, callbackCancelClose) {
    var $dialog = $('<div id="confirm_' + new Date().getTime().toString() + '"></div>');
    $dialog.html('<div>' + title + '</div><div>' + text + '<div style="width:100%;"><input type="button" id="confirmCancel" value="Cancel" style="float:right;" /><input type="button" id="confirmOk" value="OK" style="float:right;margin-right: 10px" /></div></div>');
    $('body').append($dialog);
    var buttonString = '';
    $dialog.jqxWindow({
        minWidth: 300,
        minHeight: 80,
        draggable: true,
        initContent: function () {
            $('#confirmOk').jqxButton({
                template: 'primary'
            });
            $('#confirmCancel').jqxButton({
                template: 'default'
            });
        },
        resizable: false,
        closeButtonAction: 'close',
        isModal: true,
        okButton: $('#confirmOk'),
        cancelButton: $('#confirmCancel')
    });

    $dialog.on('close', function (e) {
        console.log('1');
        if (e.args.dialogResult.OK) { //ok
            if (callbackOkClose) {
                callbackOkClose();
            }
        } else { //cancel or close
            if (callbackCancelClose) {
                callbackCancelClose();
            }
        }
    });
    return $dialog;
};

Here is a jsfiddle: http://jsfiddle.net/v0re8jeu/


Solution

  • Because you are creating that dialog for every button click, so things like $('#confirmOk') are no longer unique and return the selector for the button you clicked on first time. You should remove it from dom on close for the next one to work:

    $dialog.on('close', function (e) {
        console.log('1');
        $dialog.remove();