Search code examples
javascripthtmlpopupwindow

How to add text to a pop up window in Javascript?


I'm creating a resume builder where a person can enter information into input fields and my javascript code will take the field values and write it to a popup window, which will be their resume. I'm clearly doing something critically wrong here. I can get the pop up window to open, but no text that I'm appending from javascript is in the popup window.

I'm going to show snippets of the code so I'm not posting full-on documents, but everything follows the same suit.

The code for my input html:

<body>
    <!-- Full name -->
    <p><strong>Enter your full name:</strong></p>
    <input type="text" name="fullName" cols='75'><br>

    <!-- Address -->
    <p><strong>Enter your address:</strong></p>
    <input type="text" name="address">
     .
     .
     .
</body>

Html for my popup window:

<body>
    <div id="name"></div>

    <div id="address/phone"></div>

    <hr>

    <div class="theLeft" id="objectives_pop"></div>

    <div class="theRight" id="objectivesText"></div>
    .
    .
    .
</body>

Javascript:

function myWindow() {
    window.open("popupWindow.html", "_blank", "height=500", "width=500", "left=100", "top=100", "resizable=yes", "scrollbars=yes",
    "toolbar=yes", "menubar=no", "location=no", "directories=no", "status=yes");

    // Name
    var name = document.getElementById('fullName').value;
    document.getElementById('name').innerHTML = name;

    // Address and phone number
    var address = document.getElementById('address').value;
    var phoneNum = document.getElementById('phoneNum').value;
    document.getElementById('address/phone').innerHTML = address + '/' + phoneNum;
    .
    .
    .

I want to append text from input fields in my main html file (project.html) to the popup window in popupWindow.html. How can I do this?


Solution

  • In your current code snippet you are calling document.getElementById on the main page, not the popup. You will first need to get the popup window as a variable, then modify it as needed.

    To get you started, try doing something like the following:

    let myPopup = window.open("popupWindow.html", "_blank", "height=500", "width=500", "left=100", "top=100", "resizable=yes", "scrollbars=yes",
        "toolbar=yes", "menubar=no", "location=no", "directories=no", "status=yes");
    
    myPopup.onload = function() {
        var name = document.getElementById('fullName').value;
        myPopup.document.getElementById('name').innerHTML = name
    }
    

    This will open up a new popup window, wait for it to load, then change the name innerHTML of that popup, rather than the parent page.