Dushyant Patel’s Blog

How to access element of parent window from an iframe with jQuery

I got one requirment that need to assign value of check box which are in iframe to input box of parent window using jQuery.

I found solution which i want to share with you.

Parent Window Code:

<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>Untitled Document</title>
<script src=”js/jquery-1.3.2.js” type=”text/javascript”></script>
</head>
<body>
<form id=”form1″ name=”form1″ method=”post” action=””>
<div id=”inputbox”>
<input name=”” type=”text” id=”selectedchkbox” width=”400″ size=”50″/>
</div>
<br />
<div id=”iframe”>
<iframe src=”iframeCheckbox.html” width=”400″ height=”400″></iframe>
</div>
</form>
</body>
</html>

iframe code:

<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>Untitled Document</title>
<script src=”js/jquery-1.3.2.js” type=”text/javascript”></script>
<script type=”text/javascript”>

$(document).ready(function() {
$(“a.submitlist”).click(function() {
var newtxt = ”;
var chkbx = $(“div#checkboxlist input”)
for(var i = 0; i < chkbx.length; i ++) {
if(chkbx[i].type == ‘checkbox’ && chkbx[i].checked === true) {
if(newtxt.length !== 0) {
newtxt += ‘,’;
}
newtxt += chkbx[i].value;
}
}
parent.top.$(“input#selectedchkbox”).val(newtxt);
});
});

</script>
</head>
<body>
<form id=”form1″ name=”form1″ method=”post” action=””>
<div id=”checkboxlist”>
<p>
<input type=”checkbox” name=”checkbox1″ id=”checkbox1″ value=”checkbox1″ />
checkbox 1<br />
<input type=”checkbox” name=”checkbox2″ id=”checkbox2″ value=”checkbox2″ />
checkbox 2<br />
<input type=”checkbox” name=”checkbox3″ id=”checkbox3″ value=”checkbox3″ />
checkbox 3<br />
<input type=”checkbox” name=”checkbox4″ id=”checkbox4″ value=”checkbox4″ />
checkbox 4<br />
<input type=”checkbox” name=”checkbox5″ id=”checkbox5″ value=”checkbox5″ />
checkbox 5</p>
<p>
<label><a href=”#”>Submit</a></label>
<br />
</p>
</div>
</form>
</body>
</html>

Using “parent.top “, can target parent window and then use $(”input#selectedchkbox”).val(newtxt); to select targeted element and assign value.

Filed under: Technology

July 2009
M T W T F S S
« May   Sep »
 12345
6789101112
13141516171819
20212223242526
2728293031  

My Twitter

Error: Twitter did not respond. Please wait a few minutes and refresh this page.

del.icio.us bookmarks

Blog Stats

  • 22,973 hits

Flickr Photos

More Photos