Question

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.

Was it helpful?

Solution

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();
}

OTHER TIPS

You can bind it with the .on method, which replaced .live in a recent jQuery release. In this case you bind it to something that you know is there when the DOM is ready (like the body). Now you only need to bind once and it will fire every time you click on a #select_all.

$("body").on('click', '#select_all', function () {
    alert("clicked");  
});

http://api.jquery.com/on/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top