0

I have prepared a simple test case demonstrating my problem -

I use a jQuery UI button to open a jQuery UI dialog:

screenshot

However this works only once. On subsequent button clicks I get the error:

Uncaught Error: cannot call methods on dialog prior to initialization; attempted to call method 'open'

error in console

Even though I do initialize the dialog before the button in my code -

HTML-code:

<BUTTON ID="newBtn">New game</BUTTON>

<DIV ID="newDlg" TITLE="New game">
    Select game board:
    <BUTTON value="1">Winter</BUTTON>
    <BUTTON value="2" DISABLED>Spring</BUTTON>
    <BUTTON value="3" DISABLED>Summer</BUTTON>
    <BUTTON value="4" DISABLED>Autumn</BUTTON>
</DIV>

JavaScript:

var newDlg = $('#newDlg').dialog({
        modal: true,
        autoOpen: false,
        close: function(e, ui) {
                var bid = parseInt($(this).data('bid'));
                $(this).removeData();
                if (1 <= bid && bid <= 4) {
                        alert('selected board id: ' + bid);
                }
        },
        buttons: {
                'Close': function() {
                        $(this).dialog('close');
                }
        }
});

$('#newDlg button').button().click(function(e) {
        e.preventDefault();
        var bid = this.value;
        newDlg.data('bid', bid);
        newDlg.dialog('close');
});

var newBtn = $('#newBtn').button().click(function(e) {
        e.preventDefault();
        newDlg.dialog('open'); // also tried $('#newDlg') here!
});

I have tried using jQuery UI 1.11.4 and 1.12.1 but the problem persists.

Alexander Farber
  • 21,519
  • 75
  • 241
  • 416

1 Answers1

1

Funny story, the issue is:

  $(this).removeData();

This is removing all data attributes, including those used to define the dialog. This can be fixed by defining the specific data you want to remove:

  $(this).removeData('bid');

Then it works as expected.

Forked working example: https://jsfiddle.net/Twisty/dz8krbye/

Twisty
  • 30,304
  • 2
  • 26
  • 45