Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript Need help using localstorage

Malcolm

Administrator
Administrator
Staff Team
Code Plus
Company Plus
Hi folks,

I'm trying to play around with localstorage in JavaScript. So from my understanding to save data to local storage I use localstorage.setItem("name", "value"), however am I able to somehow pass a variable to it? For example, what I'm trying to do is when a user makes an input it stores that value into a variable which I then want to store in localstorage so that when they refresh it shows their inputted value. (Note this is merely just practice for me).

JavaScript:
var userInput;
while (userInput !== "Malcolm") {
    userInput = prompt("Enter your name!");
    localStorage.setItem("name", "value"); // Can I pass the variable userInput?
}
      
document.write(localStorage.getItem(userInput));
 
Hi folks,

I'm trying to play around with localstorage in JavaScript. So from my understanding to save data to local storage I use localstorage.setItem("name", "value"), however am I able to somehow pass a variable to it? For example, what I'm trying to do is when a user makes an input it stores that value into a variable which I then want to store in localstorage so that when they refresh it shows their inputted value. (Note this is merely just practice for me).

JavaScript:
var userInput;
while (userInput !== "Malcolm") {
    userInput = prompt("Enter your name!");
    localStorage.setItem("name", "value"); // Can I pass the variable userInput?
}
     
document.write(localStorage.getItem(userInput));

I haven't done much with localstorage, but wouldn't you want to get 'name' inside of 'userInput'?
 
Hi folks,

I'm trying to play around with localstorage in JavaScript. So from my understanding to save data to local storage I use localstorage.setItem("name", "value"), however am I able to somehow pass a variable to it? For example, what I'm trying to do is when a user makes an input it stores that value into a variable which I then want to store in localstorage so that when they refresh it shows their inputted value. (Note this is merely just practice for me).

JavaScript:
var userInput;
while (userInput !== "Malcolm") {
    userInput = prompt("Enter your name!");
    localStorage.setItem("name", "value"); // Can I pass the variable userInput?
}
     
document.write(localStorage.getItem(userInput));


Hi Malcom, just a small change :
When you set the item replace your "value" with userInput.

You need to get the item by it's key,
so in this case it is the key "name".

Code:
var userInput;
while (userInput !== "Malcolm") {
    userInput = prompt("Enter your name!");
    localStorage.setItem("name", userInput); // Store the user's input
}

document.write(localStorage.getItem("name")); // Retrieve the stored value using the key "name"
 
I haven't done much with localstorage, but wouldn't you want to get 'name' inside of 'userInput'?
Hi Malcom, just a small change :
When you set the item replace your "value" with userInput.

You need to get the item by it's key,
so in this case it is the key "name".

Code:
var userInput;
while (userInput !== "Malcolm") {
    userInput = prompt("Enter your name!");
    localStorage.setItem("name", userInput); // Store the user's input
}

document.write(localStorage.getItem("name")); // Retrieve the stored value using the key "name"
Thanks all! I'll give this a try. Appreciate the responses 🙂
 
I haven't done much with localstorage, but wouldn't you want to get 'name' inside of 'userInput'?
Are you referring to something like this?
JavaScript:
var userinput = {
    name: "user name"
}

console.log(localStorage.setItem("userInput", name);

Hi Malcom, just a small change :
When you set the item replace your "value" with userInput.

You need to get the item by it's key,
so in this case it is the key "name".

Code:
var userInput;
while (userInput !== "Malcolm") {
    userInput = prompt("Enter your name!");
    localStorage.setItem("name", userInput); // Store the user's input
}

document.write(localStorage.getItem("name")); // Retrieve the stored value using the key "name"
So pretty much the key is the "name" of the variable that's stored in the browser storage, the value followed right after is the content we want to be stored. And when we want to call it, we simply just call the key name using localStorage.getItem("name");?
 
As I said, I haven't done much with localstorage. Maybe this can help:

Thank you!

So after a bit of testing I was able to get the localStorage working 'partly'. Now the general concept I was able to get working, I'm able to store an inputted value from the user into localStorage. However the way it is currently stored is posing a few issues but I do believe I would be able to resolve this using a loop.

Here is the code (Mostly sharing just to show the concept):
JavaScript:
function sendMessage() {
    var text = document.getElementById("textField").value;
    var messages = [];

    messages.push(
        (document.getElementById("messages").innerHTML += text + "<br>")
    );
    localStorage.setItem("messages", JSON.stringify(messages));
}

var historyRaw = JSON.parse(localStorage.getItem("messages"));

console.log(historyRaw);
 
Thank you!

So after a bit of testing I was able to get the localStorage working 'partly'. Now the general concept I was able to get working, I'm able to store an inputted value from the user into localStorage. However the way it is currently stored is posing a few issues but I do believe I would be able to resolve this using a loop.

Here is the code (Mostly sharing just to show the concept):
JavaScript:
function sendMessage() {
    var text = document.getElementById("textField").value;
    var messages = [];

    messages.push(
        (document.getElementById("messages").innerHTML += text + "<br>")
    );
    localStorage.setItem("messages", JSON.stringify(messages));
}

var historyRaw = JSON.parse(localStorage.getItem("messages"));

console.log(historyRaw);
Was able to get this all working.

Here's how it works:
  1. Upon submitting, sendMessage() function is called.
  2. This function will store the inputted text in a variable.
  3. Then it will push the value into the messages array.
  4. displayMessages() is then called.
  5. This function stores the div info with id "messages", a newly create P tag and the messages array converted into a string.
  6. It will then store that was converted into a string into localStorage.
  7. Then a for loop is executed which goes through each message and creates a new paragraph for it.
  8. Outside the function getMessages is called, which stores the data from localStorage, parses it into json and stores the div info from messages.
  9. Then a loop is executed, which goes through each array item of historyArray, which creates a new tag each time and inserts the array value into it.
  10. The tag is then added to the page using append.
Some quick notes:
  • FYI at the time of this message I am pretty tired.
  • This code isn't perfect, there's some inefficiencies that caught my eye.
  • Each message should be stored in localStorage upon being sent. Currently it's stored when displayMessages() is called which doesn't make sense.
  • I pass messages through to getMessages(messages) but don't do anything with it.
  • New messages display at the bottom, rather than the top.
  • After refresh, the previously stored messages are gone. Most likely because we're overwriting it (Need to be careful as we would need to eventually dump localStorage as it could use up memory, but not after sending a message and reloading).
  • Probably missing some more but will review tomorrow.

HTML:
<body>
    <input id="textField" type="text" />
    <button id="submitBtn" onclick="sendMessage();">Submit</button>

    <div id="messages"></div>
    <script>
        var messages = [];

        function sendMessage() {
            var text = document.getElementById("textField").value;

            messages.push(text);
            displayMessages();
        }

        function displayMessages() {
            var history = document.getElementById("messages");
            var createPTag = document.createElement("p");
            var messagesString = JSON.stringify(messages);
            localStorage.setItem("messages", messagesString);

            for (var i = 0; i < messages.length; i++) {
                createPTag.textContent = document.getElementById(
                    "messages"
                ).value = messages[i];
                history.appendChild(createPTag);
            }
        }

        function getMessages(messages) {
            var historyRaw = localStorage.getItem("messages");
            var historyArray = JSON.parse(historyRaw);
            var history = document.getElementById("messages");

            for (var i = 0; i < historyArray.length; i++) {
                var createPTag = document.createElement("p");
                createPTag.textContent = historyArray[i];
                history.appendChild(createPTag);
            }
        }

        getMessages(messages);
    </script>
</body>
 

New Threads

Buy us a coffee!

Back
Top Bottom