Rex Butler
Rex Butler

Reputation: 1060

Iframe DOM Problem: undefined values when accessing form field

I've been having trouble debugging some JavaScript which normally would seem easy to fix. I've tried several methods, some based on using a form to access fields, other ways by using getElementById. I've also messed around with leaving in/out the name attributes in several places.

In the Iframe File, asdf_iframe.html:

    <form id="asdf_form" name="asdf_form" action="asdf_iframe.html">
      <input type="hidden" id="field_1">
    </form>

In the base file:

    <iframe id="asdf_iframe" name="asdf_iframe" src="asdf_iframe.html" height="50" width="50">
    </iframe>

    <script>
      function get_iframe_doc(_window,frame_id) {
        var frame_elem = _window.document.getElementById(frame_id);
        if(frame_elem.contentDocument)
          return frame_elem.contentDocument;
        else
          return frame_elem.contentWindow.document;
      }
    </script>

    <script>
      var asdf_iframe_doc = get_iframe_doc(this,"asdf_iframe"); //Profiler says this is defined
      asdf_iframe_doc.getElementById("field_1").value = 1234;   // Error Here: not defined
    </script>

I've tried many different methods of accessing field_1, but with no success.

Upvotes: 0

Views: 1994

Answers (2)

Ruan Mendes
Ruan Mendes

Reputation: 92274

To me, it seems you are calling

asdf_iframe_doc.getElementById("field_1").value = 1234;

Too early. You need to call that method after the iframe finished loading its url.

Here's an attempt.

window.onload = function() {
    var iframe = window.frames["asdf_iframe"];
    iframe.onload = function() {
        iframe.document.getElementById('field_1').value = 1234;
    }
}

Upvotes: 3

Alohci
Alohci

Reputation: 82976

Your script is simply running too soon. Try this instead.

<script>
window.onload = function() {
  var asdf_iframe_doc = get_iframe_doc(this,"asdf_iframe");
  asdf_iframe_doc.getElementById("field_1").value = 1234;
}
</script>

Upvotes: 1

Related Questions