Advaith Advaith - 6 months ago 16
MySQL Question

LocalStorage error

I am not able to save the text which is being copied on the button press after reloading the page so that i can remember what i typed before.

My Code:

<html>
<body>
<input type="text" id="txt">
<input type="button" onclick="myFunction()">
<p id="p"></p>
<script>
function myFunction() {
document.getElementById('p').innerHTML = document.getElementById('txt').value;

if (typeof(Storage) !== "undefined") {
localStorage.setItem("myinputvalue", document.getElementById("p")[0].innerHTML);
localStorage.getItem("myinputvalue");
}
}
</script>
</body>
</html>

Answer

It has to be document.getElementById("p").innerHTML. document.getElementById does not return NODE LIST. So there is no need of [0].

function myFunction() {
    document.getElementById('p').innerHTML = document.getElementById('txt').value;

    if (typeof(Storage) !== "undefined") {
        localStorage.setItem("myinputvalue", document.getElementById("p").innerHTML);
        console.log(localStorage.getItem("myinputvalue"))
    }
} 

Check this JSFiddle.