Accessing parent local variable in child window

I would like to use the local variable of the parent in the child window. I have used parent.window.opener

but it returns undefined

.

This is my code:              

<script type="text/javascript">
 var selectedVal;

 $(document).ready(function () {
  //....
  //...
   if ($(this).val() == "byActor"){
           $("#tags").focus();
           $("#tags").autocomplete({
             source: "actorsauto.php",
             minLength: 2,
             focus: function( event, ui ){
                   event.preventDefault(); 
                   return false;
             },
             select: function (event, ui){ 
                       var selectedVal = ui.item.value;
                       alert(selectedVal);
                   }
            }); 
   });

$('#btnRight').on('click', function (e) {
         popupCenter("movieByactor.php","_blank","400","400");
});
</script>
 </body>
 </html>

      

and this is a child:

<body>
 <script type="text/javascript">

  var selectedVal = parent.window.opener.selectedVal; 
   alert(selectedVal);

 </script>
</body>

      

+3


source to share


2 answers


You can't - the whole idea with local variables is that they are only available to the extent that they are declared and function within that function.

In your case, the choice selectedVal

is only available inside this function declaration:

select: function (event, ui){ 
   var selectedVal = ui.item.value;
   alert(selectedVal);
}

      

To use it outside of this scope, you need to make it global by attaching it to a window:



window.selectedVal = 'somevalue';

      

You can also make variables implicitly global by leaving out the keyword var

, however this is bad practice and is not allowed in strict mode.

This will allow you to access window.selectedVal

:

window.opener.selectedVal // for windows opened with window.open()
window.parent.selectedVal // iframe parent document

      

+6


source


try this:



<body>
    <script type="text/javascript">

        var selectedVal = window.opener.selectedVal; 
        alert(selectedVal);

    </script>
</body>

      

-2


source







All Articles