views:

83

answers:

3

I open an ajax modal window with jQuery. How can I update the DOM and make the new elements available for jQuery to use?

A: 

Give the window an ID and just reference it in jQuery like $('#modalWindow').

To access elements inside the modal window, use the same notation: $('#modalWindow .whatever').

You can put any valid CSS selector in $(). See the jQuery() documentation for more help.

sirlancelot
I was talking about the elements inside the modal window. They are dynamic, generated with an ajax request.
Dudul
As long as YOU know the names of the elements you can still select them the same way: `$('#modalWindow *')`
sirlancelot
wow, jquery searches multiple DOMs?
Juan Mendes
A: 

As soon as you manipulate the DOM you can reference its elements:

// add a new div to the body
$('<div id="just_added">').appendTo('body');

// make the new div you just added explode
$('#just_added').explode();
Scott Evernden
A: 

Here's a jsFiddle I put together that dynamically creates a jQueryUI modal (I'm assuming that's what you using - if not, please update your question with more details about that, please).

Basically what I'm doing is creating my container and message/form in my JavaScript:

var theDialog = $("<div id='msg'>");
theDialog.append("<div><label for='txtVal'>Enter a Value:</label><input type='text' id='txtVal'/></div>");

Then I use the jQuery UI dialog control to instantiate the modal and display it. I'm also collecting information on it and passing it back (sort of) to the parent page.

Hopefully this is what you're looking to do. Please let me know if there are other questions and I'll update my answer accordingly.

Hope this helps!


CODE
BTW, this isn't optimized -- it's purely for demo purposes. Don't use in production!

HTML:

<div id="content">
  <span>Click here for the modal:<button id="openModal">Open</button></span>
  <br/>
  <span>Results:<input id="theResults" type="text" />
</div>​

JavaScript:

    $(document).ready(function() {
        $("#openModal").click(function(e) {
            e.preventDefault();
            openDialog();
        });
    });

    function openDialog() {
        var theDialog = $("<div id='msg'>");
        theDialog.append("<div><label for='txtVal'>Enter a Value:</label><input type='text' id='txtVal'/></div>");
        $(theDialog).dialog({
            title: "Sample Dialog",
            modal: true,
            buttons: { "Cancel": function() { 
                                $(this).dialog("destroy"); 
                                $("#msg").remove(); 
                            },
                       "Save": function() { 
                               $("#theResults").empty();
                               $("#theResults").val($("#txtVal").val());
                               $(this).dialog("destroy"); 
                               $("#msg").remove();
                           }
                     }
        });
    }
​
David Hoerster