How to bind events to components on a modal dialog?

Nicsoft picture Nicsoft · Jul 24, 2012 · Viewed 11.1k times · Source

I am using jQuery's modal dialog for opening a dialog containing a form. What I cannot solve is how to bind events to components that is added to my modal dialog. In this case, I want to bind click or change to a checkbox that has been positioned in the dialog. There doesn't seem to be any success-method that is triggered when the dialog has been loaded. This is how I do it:

This I do in the beginning of my javascript, in the beginning of the ready-function:

$( "#dialog:ui-dialog" ).dialog( "destroy" );

$( "#dialog-modal" ).dialog({
    autoOpen: false,
    show: "blind",
    hide: "explode",
    minWidth: 400,
    modal: true
 });

A bit later I do this when clicking a button:

$('#dialog-modal').dialog( "option", "title", lang.localized_text.ADD_AGENT);
$('#dialog-modal').live('dialogopen', function(msg){
        alert("Opens");
        $("#select_all").live('click', function(msg){
               alert("clicked");  
        });

 });
$.get("https://" + hostname +  "/modules/core/useradmin/adminactivities/admin_add_agent.php",function(e){
     var obj = $.parseJSON(e);
     $("#dialog-modal").html(obj.html);
     $("#dialog-modal").dialog("open");
     addAddAgentValidation();
}
});

One can clearly see that alert("Opens") is presented before the dialog is opened. Hence, dialogopen is triggered before the dialog has finished loading. But the validation handler (calls the validate function which binds the validation checks) works.

alert("clicked"); is never triggered.

How can I bind any event to a component on the modal dialog? Is there any callback function when the dialog has been created.

Answer

Shikiryu picture Shikiryu · Jul 24, 2012

Since your select will be in #dialog-modal and since #dialog-modal is present on domready (and never destroyed ?), you could use $.on()

$('#dialog-modal').on('click', '#select_all', function(e){
    alert('clicked');
});

But you could also bind the click event when you include #select_all into the dom.

$.get("https://" + hostname +  "/modules/core/useradmin/adminactivities/admin_add_agent.php",function(e){
     var obj = $.parseJSON(e);
     $("#dialog-modal").html(obj.html);
     $('#select_all').click(function(e){
         alert('clicked');
     });
     $("#dialog-modal").dialog("open");
     addAddAgentValidation();
}