Can't pass value from window.opener to its parent

2.2k Views Asked by At

I have a button that when pressed opens a new window, in that window the user chooses a file and clicks it. When clicked, the value should pass to a hidden input in the form and closes the window. Everything acts like it should be, the only thing that its not working, is the fact that the input value stays empty.

This is my input:

<input name="value_pdf" value="" type="hidden" id="value_pdf" />

And here is the function:

$(".insert").click(
    function () {
            var file = $(this).attr("rel"); //its correct and passes the value I want
            var value = "value_<?php echo $_GET['but'];?>" //again, this is correct too, I've used console.log() to check

            opener.$("#value_pdf").val(file);
            //I've done a console.log() here to to check if #value_pdf had a value and it was correct, it logged something like "database.pdf"

            window.close();
            return false;
    }
);

My question is, where did I do it wrong? I seems that everything is right...

EDIT: Turns out, somewhere in my code I had this same ID on a DIV. Althought I advise you to check the choosen answer if you have this same problem, it made my code better.

2

There are 2 best solutions below

6
On BEST ANSWER

I've never tried opener.$(...) but it looks like it should work, providing the opener window still exists and there's no cross-domain issue.

If it doesn't work then you might try writing a function in the opener and calling it from the child window.

In the opener (in the global namespace or in some namespace accessible from global) :

function setValue(selector, value) {
    $(selector).val(value);
}

In the child window :

window.opener.setValue("#value_pdf", file);

I can't really see why this would work when opener.$(...) didn't because there's no fundamental difference. But hey, you never know ...

1
On

If you have php enabled I would use that instead of sending via javascript. And if you need the information on the same page, i would use AJAX.

http://api.jquery.com/jquery.post/

a sample would look like this.

$.post( "test.php", $( "#testform" ).serialize() );
<form id="testform">
<input name="something">
</form>

This would take a form and submit the input named "something" and post it to the "test.php" page.