Question

Um I trying to save the messages in "textBox" back in to localStorage and prepend it to "logContent" but when I refreshed the page the "logContent" is still empty with only original content exists.

<body>

<div class="modal-body"> 
    <input id="textBox" type="text" placeholder="Type Message" onkeydown="if (event.keyCode == 13) {enterPressed();}">
    <p id="logContent">
            -- Logging is created --
    </p>
</div>

</body>

Here is my Javascript so I want to replace original content in "logContent" with textBox.value + original content in logContent and make display everything all the time even with you refresh the page. Thank you.

var today = new Date(); 
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0
var yyyy = today.getFullYear();

if (dd < 10) {
dd ='0'+ dd
} 

if (mm < 10) {
mm ='0'+ mm
} 

today = dd + '/' + mm + '/' + yyyy;

function enterPressed() {
localStorage.setItem("logs", document.getElementById("textBox").value);
if (textBox.value == "") {

}
else {
var logText = today + ":" + " " + localStorage.getItem("logs") + '<br>';
$("#logContent").prepend(logText); // Prepend textBox's content to the top of  "logContent".
textBox.value = ""; // To clear the textBox after enter is pressed.
}
}
Was it helpful?

Solution

The original script did not provide the means to load the logs from localStorage, and stored new input under the "logs" key, while the intent was to prepend. The solution is quite simple: load from localStorage on page load, and overwrite localStorage['logs'] with the contents of logContents as displayed on the page.

....

window.onload = function(){
    existing_log = localStorage.getItem("logs");
    console.log(existing_log);
    if (existing_log){document.getElementById("logContent").innerHTML = existing_log;}
}

function enterPressed() {
    if (textBox.value == "") {
        return;
    }
    else {
        var logText = today + ":" + " " + document.getElementById("textBox").value + '<br>\n';
        $("#logContent").prepend(logText); // Prepend textBox's content to the top of  "logContent".
        textBox.value = ""; // To clear the textBox after enter is pressed.
        localStorage.setItem("logs", document.getElementById("logContent").innerHTML);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top