Eightleven Eightleven - 4 months ago 17
Javascript Question

accessing id element of parent page from iframe

How can I access id element from iframe to parent page? I have tried to use this method but still not work.

Parent.html


<html>
<head>
<title>Parent</title>
</head>
<body>
<button id="click" onclick="alert('Hello');">click</button>
<iframe id="iframe1" src="iframe.html">
</iframe>
</body>
</html>


iframe.html

<!DOCTYPE html>
<html>
<head>
<title>Parent</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.1.0.slim.js"></script>
<script>
$(function() {
var money = 20000;

$("#nominal").on("change keyup", function() {
var input = $(this);

// remove possible existing message
if( input.next().is("form") )
input.next().remove();

// show message
if( input.val() > money )
window.parent.$('#click').trigger('click');
});
});
</script>
</head>
<body>
<input type="text" id="nominal">
</body>
</html>


Whether there is something wrong with the script I created? Please help me to improve this code. Thanks in advance.

PROBLEM SOLVED

Answer

You are attempting to use jQuery on the parent window although it is not defined in that context. It is only defined in the child document.

Instead change your child iframe script to call jQuery on the parent window's element. Here's an example:

Parent Document

<html>
  <head>
    <title>Parent</title>
  </head>
  <body>
    <button id="click" onclick="alert('Hello')">click</button>
    <iframe id="iframe1" src="iframe.html">
    </iframe>
  </body>
</html>

Child (Iframe) Document

<!DOCTYPE html>
<html>
  <head>
    <title>Parent</title>
    <script type="text/javascript" src="//code.jquery.com/jquery-3.1.0.slim.js"></script>
  </head>
  <body> 
    <input type="text" id="nominal">

    <script>
      $(function() {
          var money = 20000;

          $("#nominal").on("change keyup", function() {
              var input = $(this);

              // remove possible existing message
              if (input.next().is("form")) {
                  input.next().remove();
              }

              // show message
              if (input.val() > money) {
                $(window.parent.document.getElementById('click')).trigger('click');
              }
          });
      });
    </script>
  </body>
</html>

https://plnkr.co/edit/ks8oFmQyxHYFt0h8eBbF?p=preview

Alternatively

You could also drop jQuery altogether for something as simple as triggering a click:

// replace this
$(window.parent.document.getElementById('click')).trigger('click');

// with this
window.parent.document.getElementById('click').click();

A note on safety: this is a fairly brittle approach in that you must know that a specific element exists in the parent document with that specific id attribute. It would be better to at least have some checks for existence before calling click on a node that may not be present.