Reputation: 13206
I have two documents - main.html (parent document) and enterKey.html (child document).
Within main.html
<script>
...
</script>
<iframe id="key" src="enterKey.html"></iframe>
Within enterKey.html:
<input id="sbox" type="text">
I am trying to access the value entered in sbox for use in main.html. But because the user will be continuously updating sbox I need for the updates to be reflected in main.html.
For example if the user types into sbox "hello worlx" then corrects it a second later to "hello world" then the change must be reflected immediately in the parent document.
How can this be achieved?
I've been looking at using document.getElementById('key').contentWindow.sbox
but don't know how to use it in the context of my example.
Many thanks in advance!
Upvotes: 0
Views: 4898
Reputation: 2166
I think the best approach would be to set the onchange function on the field and they you can access elements on the parent page with:
parent.document.getElementById("id")
Example:
In the enterKey.html you would set the onchange for your text field by:
<input id="sbox" type="text" onChange="enterKeyFunc()">
Then also in enterKey.html you would have a function called enterKeyFunc() or something that would look kinda like this:
function enterKeyFunc()
{
parent.document.getElementById("mainHTMLFieldId").value = document.getElementById("sbox").value;
}
Then in main.html make sure that the field you wanted to keep synced has an id of "mainHTMLFieldID" and that should do it. Let me know if you have any other questions.
Edit again:
I think if you want to set a variable in the parent change the above js from
parent.document.getElementById("mainHTMLFieldId").value = document.getElementById("sbox").value;
to
parent.globalVariableName = document.getElementById("sbox").value;
This of course would only work if the variable you are trying to set is a global variable on the parent page. I haven't done this for a long time personally but I believe this can be done.
Upvotes: 2
Reputation: 298236
It's a bit more simple than you think:
var iframe = document.getElementById('key').contentWindow;
var value = iframe.getElementById('sbox').value;
Just treat the iframe
as a new document
element.
Upvotes: 2