DonKain DonKain - 18 days ago 5
CSS Question

Save and open the content of a textarea

i'm working on a text editor as part of a school project and i'm having a small issue with my save and open code.

Here are my buttons:

<button id="gu" onclick="save()">Save</button>
<button id="ab" onclick="open()">Open</button>


Here's my textarea:

textarea name="comment" rows=30 cols=101 id="texto"></textarea>


And here's my javascript functions:

function save()
{
gu = document.getElementById("texto");
localStorage.setItem("texto",gu);
console.log(texto+"="+gu);

}

function open()
{

console.log("Abierto")
document.getElementById('texto').innerHTML=gu;
}


My goal is that if write something and then press the "save" button, the content inside my textarea is saved, and if i press the "open" button it shows what i wrote on the textarea.

Any idea on how to fix my code?

Sorry if my english is bad.

Answer

Here you go: https://jsfiddle.net/cinerobert/qwgv18r5/

function save()
{
    localStorage.setItem("someitem", document.getElementById("texto").value);
    document.getElementById("texto").value = "";
    console.log(texto + "=" + gu);
}

function retrieve(){
        console.log("Abierto")
        document.getElementById("texto").value = localStorage.getItem("someitem");
}

You can't use open() as a function name because it's already a built-in function in javascript, so I changed it to retrieve(). See here: http://www.w3schools.com/jsref/met_win_open.asp

Is there some reason you're required to use setItem()? Using a variable (gu) and setItem is redundant. It would work either way.

Also to get and set the text inside a text area I you need to use value().

I also changed the save() function so that it clears the textbox, so that you can see something happen when you click retrieve().