0

I just started learning javascript. What I want to do is store the value of an input after I press "Save" inside a button using localStorage and change its name. Thanks.

Example Screenshot

<h3 id="titlu" class="bh">Chat</h3>
<input type="button" name="userName" id="Uname" class="Uname" value="Username"/>
<div id="popUp">
    <p>Set your username:</p>
    <input type="text" name="setusername" id="userSet">
    <input type="button" id="save" class="pophide" name="save" value="save"/>
</div>

$(document).ready(function(){
    $("#save").click(function(){
        var valoare = $("#userSet").val();
        if (typeof(Storage) !== "undefined") {
            // Store
            localStorage.user = valoare;
            // Retrieve
            document.getElementById("Uname").innerHTML = localStorage.user;
        } else {
            document.getElementById("Uname").innerHTML = "Sorry, your browser does not support Web Storage...";
       }
    });
})
Rhumborl
  • 16,349
  • 4
  • 39
  • 45
Bogdan Laza
  • 67
  • 1
  • 1
  • 11

1 Answers1

1

Your code is generally fine. The only real problem I can see is how you are setting the text at the end.

As Uname is an <input type="button">, you use it in a similar way to <input type="text">. To change the text displayed, you need to set it's value property, not innerHTML.

As you are using jQuery, you can use val() as you did to read the input value earlier:

$("#Uname").val(localStorage.user);

A second small point. It is generally fine to use localStorage.user, but it is safer to use the standard calls, setItem() and getItem() to avoid conflicting with an existing property of the Storage object, e.g. localStorage.setItem = 'My Set Item' will cause you problems.

The following should work for you:

$(document).ready(function(){
    // display previous stored username, if set
    var prevUname = localStorage.getItem("user");
    if(prevUname !== null) {
        $("#Uname").val(localStorage.getItem("user"));
    }

    $("#save").click(function(){
        var valoare = $("#userSet").val();
        if (typeof(Storage) !== "undefined") {
            // Store
            localStorage.setItem("user", valoare);

            // Retrieve
            $("#Uname").val(localStorage.getItem("user"));
        } else {
            $("#Uname").val("Sorry, your browser does not support Web Storage...");
       }
    });
})

Working jsFiddle

Rhumborl
  • 16,349
  • 4
  • 39
  • 45
  • Your a life saver :D Thank You , another thing if you may , If the user have never been on the page , i want him to see the value of the button as Username before he types something and saves it inside. Hope you understand what i wrote. Thanks again :). – Bogdan Laza Mar 01 '16 at 09:33
  • No problem. You just need to check if the first `localStorage.getItem("user")` is null or not. Have updated the code to handle this. – Rhumborl Mar 01 '16 at 09:38
  • Thanks a lot :) . Cheers – Bogdan Laza Mar 01 '16 at 09:39