Sunday 6 September 2009

Access IFrame content using Jquery

This is really helpful post for so many people who are using frames in their pages and want to access content inside it from main[parent] page. I really faced so many problems to read the data inside a frame and use it on the current page. So, it's simple and nice to know this tip for JQuery lovers.

HTML:

In Parent file, for example iFrame is declared as below.

<iframe id="uploadIFrame" scrolling="no" frameborder="0" hidefocus="true" style="text-align: center;vertical-align: top; border-style: none; margin: 0px; width: 100%; height: 60px;" src="IFrameExample.htm"></iframe>

In IFrameExample.htm, assume there is a hidden control as shown below.

<input type="hidden" id="hiddenExample" name="hiddenExample" />

So, now I will tell you how to set the "hiddenExample" hidden control value from the parent file. Because, we can’t directly access it through java script/HTML. We need to use below logic to get it working.

var $currentIFrame = $('#uploadIFrame');
$currentIFrame.contents().find("body #hiddenExample").val("Value from parent file.");

That's it!!! You are done with assigning some value to hidden variable inside IFrame. And in that iFrame you can access this hidden control on server side[C# or VB etc..] too. For it, you need to follow my other post. Very simple, but hard to find. Below is the nice explanation of above code. [How it will work.]

So, we are using Jquery, you know how to define JQuery object and use it in DOM. I created a variable[Object] currentIFrame which holds the whole IFrame reference. And in the second line, I am using the contents() method, which actually returns me all the HTML code of the frame. So, as we already know, find is the method we need to use to find out any element in a given scope/context. So, it tries to find out the occurrence of given criteria in current frame. I think you understood well how it works. If you are having multiple IFrames then you can define class for <iframe> instead of id and you can catch it in Jquery by using "." operator instead of "#". Is it a new and good find? Please let me know, if this helps you or any questions if you have.

No comments:

Post a Comment