cola465
cola465

Reputation: 113

Transferring variables across HTML pages

I am taking in an input from a text box in one HTML page and saving it to local storage using this function.

function writeMail(emailInput){
console.log(emailInput);
localStorage.setItem('emailInput',emailInput);
let theEmail = localStorage.getItem('emailInput');
console.log(theEmail);

}

This works fine and I can check the inputs are correct through my console logs. Yet when I try and get this from local storage to store in my table in my emailList html file, it seems to not work at all.

<body>

email = localstorage["emailInput"];

<table>
    <caption> Email list
    </caption>
    <tr>
    <th> Name </th>
    <th> Email </th>
    </tr>
    <tr>
        <td>email </td>
    </tr>
</table>
</body>

Upvotes: 0

Views: 65

Answers (1)

Telmo Dias
Telmo Dias

Reputation: 4178

For you to be able to manipulate the contents of HTML, you need to modify the DOM node specifically. In this specific case you should have an id attribute on the <td>and then use the innerHTML property of that node to set the desired value.

i.e.:

<td id="xpto"></td>

then on the code:

let theEmail = localStorage.getItem('emailInput');
document.getElementById("xpto").innerHTML = theEmail;

You should also set that code inside of a function that is called once the document has finished loading, so something like:

JAVASCRIPT:

function go(){
   let theEmail = localStorage.getItem('emailInput');
   document.getElementById("xpto").innerHTML = theEmail;
}

HTML:

<body onload="go()">

Upvotes: 2

Related Questions