Search code examples
javascriptjqueryjquery-uijquery-ui-dialog

JQuery - How to target correct button in multiple JQuery cloned Dialogs?


I am cloning multiple instances of a JQuery Dialog:

$('#button').click(function() {
    $('.dialog').clone().appendTo('body').removeClass('dialog').dialog({
        width: '300',
        height: '200',
        dialogClass: 'dialogClass',
        open: function(event, ui) {
            $(".dialogClass").children(".ui-dialog-titlebar").append("<button class='dialog_pdf_button' type='button'>PDF</button>");
        }
    });
});

On Dialog open, I am then appending a button with class='dialog_pdf_button' to the cloned Dialog title bar.

enter image description here

I need to target the correct PDF button on the cloned Dialogs to perform an action (save text in Dialog to PDF...) on click of the related PDF button.

How can I find and target for a click event on the correct PDF buttons in the cloned Dialogs?

See Fiddle


Solution

  • Just bind events to element before append.

    $(".dialogClass").children(".ui-dialog-titlebar").append(function () {
      var button = $("<button class='dialog_pdf_button' type='button'>PDF</button>");
      button.click(function () {
        // Event handler
      });
    
      // Or other event..
    
      return button;
    });
    

    You can create jquery element dynamically with $(HTML_TEMPLATE)