Sandra
Sandra

Reputation: 115

Accessing elements of parent window from iframe (jquery)

I have several dinamically created divs, with the same elements inside:

<div id="(dinamic_id_1)">
    <div class="(element_1)">Some text here</div>
    <input class="(element_2)" />
    <iframe class="(element_3)" src="form.php?id=(dinamic_id_1)" />
</div>

<div id="(dinamic_id_2)">
    <div class="(element_1)">Some text here</div>
    <input class="(element_2)" />
    <iframe class="(element_3)" src="form.php?id=(dinamic_id_2)" />
</div>

...

And there's a form within the iframe that would look something like this:

<form id="(dinamic_id)" >
    <input class="(class_input)" />
</form>

And my jquery function:

$(".class_input").change(function() {
    $(this).closest("form").submit();
});

There are other actions that I want to execute on submit on the parent window, on the elements contained within the div that shares the same id as the form. I got to get the html within the parent div like this:

var parent_div = $("div#"+$(this).closest("form").attr("id"), parent.document);
alert($(parent_div).html());

But I can't get to the elements within the div, for example:

var parent_div = $("div#"+$(this).closest("form").attr("id"), parent.document);
alert($(parent_div+" .element_1").html());

or

var parent_div = $("div#"+$(this).closest("form").attr("id")+" .element_1", parent.document);
alert($(parent_div).html());

Return null instead of "Some text here".

Upvotes: 7

Views: 11562

Answers (1)

Goran Mottram
Goran Mottram

Reputation: 6304

Try modifying the code to the following:

var parent_div = $("div#"+$(this).closest("form").attr("id"), parent.document);
alert(parent_div.children('.element_1').text());

I knocked up a quick test my end and all worked fine.

Edit: Explanation

The problem is that you were trying to reference parent_div as a string, when in fact it is a jQuery object on it's own.

alert($(parent_div + " .element_1").html());
//     ( [object]  +    [string]  )

Upvotes: 2

Related Questions