Setting Focus to Control in an IFRAME using JQuery

Had a gnarly problem this afternoon, while trying to set focus to a control in an IFRAME.

Using JQuery, I had created the IFRAME with the JQuery plugin ThickBox. ThickBox provides functionality that can simulate a modal dialog using an IFRAME, loading a page from a URL into the IFRAME (check out the demo here - scroll down to "Inline Content"). The page loaded inside the IFRAME contained code to set the focus which was actually being called, but after the page loaded something else was stealing the focus.

I began to look at the javascript code in the parent that created the IFRAME.

I discovered to set the focus to a control in an IFRAME that has already been loaded, you need to set the focus to the IFRAME first (thanks Alex King). I also benefited from "How to access IFRAME in JQuery" over at ProCoding (thanks Taras Ilnytskyy).

Here's the code to set focus to a control in an IFRAME using JQuery (called from the parent window, after the IFRAME has been loaded and shown):
	
//get the IFRAME element - note no hashes in the name, we're using browser functionality
var iframeRef = document.getElementById("IFRAMEID");
//focus the IFRAME element
$(iframeRef).focus();
//use JQuery to find the control in the IFRAME and set focus
$(iframeRef).contents().find("#CONTROLID").focus();
I hope this helps someone!

UPDATE: Fixed formatting.

Tags: , , ,

posted @ Thursday, May 28, 2009 2:58 PM

Print

Comments on this entry:

# re: Setting Focus to Control in an IFRAME using JQuery

Left by Manjunath at 7/15/2009 4:06 PM
Gravatar
Thanks for the code, but for some reason it is not working.

Below is the piece of code, that i am using. Any help on this would be great.

var iframeRef = document.getElementById("TB_iframeContent");
$(iframeRef).focus();
$(iframeRef).contents().find("#CategoryNameTextBox").focus();

# re: Setting Focus to Control in an IFRAME using JQuery

Left by Thomas Williams at 7/15/2009 6:00 PM
Gravatar
Hi Manjunath - a couple of questions: what error are you getting? What version of JQuery are you running? What browser are you using?
Comments have been closed on this topic.
«September»
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789