0

I am working on a simple page that contains 2 iframes. Text is input into iframeA and once a button is clicked on iframeB I want it to display the text from iframeA but it just displays undefined. I feel like I am close but cannot seem to see what I am doing wrong. The code for both iframe pages is below.

--iframeA (ifr1.htm)
<html>
<head>
    <script type="text/javascript">
    var var_name = document.getElementById("textbox").value;
    </script>
<body>
<input type="text" name"textbox" id="textbox"/>
</body>
</html>


--iframeB (ifr2.htm)
<html>
<body>
    <script type="text/javascript">
    function f2(txt){
    var name2 = parent.ifr1.var_name;
    document.getElementById('div2').innerHTML = name2;
    }
    </script>
    <div id="div2"></div>
    <button onclick="f2('complete')"></button>
</body>
</html>
  • could be a race condition. at the time the frameB code runs, frame A might not have completed loading, so `var_name` isn't defined yet. – Marc B Sep 09 '14 at 21:01

1 Answers1

0
parent.ifr1.var_name;

I would recommend parent.frames.ifr1.var_name

it just displays undefined:

var var_name = document.getElementById("textbox").value;</script>
</script>
…
<input type="text" name"textbox" id="textbox"/>

You're assigning the value of the input only once, when the document is loading (I doubt that it works at all actually). When you later type anything in, the value of var_name never changes.

Instead, you want to get the value when the button is clicked:

function f2(txt){
    var name2 = parent.frames.ifr1.document.getElementById("textbox").value;
    document.getElementById('div2').innerHTML = name2;
}

(and you can remove the script from ifr1.htm). Alternatively, use this for the first iframe:

<html>
<head>
<body>
    <input type="text" name"textbox" id="textbox"/>
    <script type="text/javascript">
    var var_name;
    document.getElementById("textbox").onchange = function(e) {
         var_name = this.value;
    };
    </script>
</body>
</html>
Community
  • 1
  • 1
Bergi
  • 513,640
  • 108
  • 821
  • 1,164
  • This worked! What if i wanted to have the frame display a input from a text box on the main page, and eliminate iframeA, is that difficult to do? – user3385236 Sep 09 '14 at 21:17
  • No. You would simply access `parent` instead of `parent.frames.ifrm1`; and what I said about the input now holds equally for the parent window. – Bergi Sep 09 '14 at 21:19