1

with this function:

function appendToStorage(name, data) {
    var old = localStorage.getItem(name);
    if (old === null) old = '';
    localStorage.setItem(name, old + data);
}
appendToStorage('oldData', $('textbox').value);

and this html:

<textarea name ="textbox" cols="50" rows="5">
say it...
</textarea><br>

<input type="submit" onclick="appendToStorage(name, data)"/>

I get undefinedundefinedundefined... on the console.

what I am missing?

Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
8-Bit Borges
  • 9,643
  • 29
  • 101
  • 198

2 Answers2

2

You need to pass the textarea's value, and the storage key to appendToStorage.

So it is better to use a another method which does that an call that on click of the button like

<input type="submit" onclick="addTextArea();" />

then

function appendToStorage(name, data) {
    var old = localStorage.getItem(name);
    if (old === null) old = '';
    localStorage.setItem(name, old + data);
}
addTextArea();

function addTextArea() {
    appendToStorage('oldData', $('textarea[name="textbox"]').val());//use .val() to get the value, also need to use attribute selecotr for name
}

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

It's hard to tell what you're trying to achieve here, however the easiest solution is to let your appendToStorage function do the work:

function appendToStorage (name) {
  
  // get the target element by it's name
  var el = document.querySelector('[name="' + name + '"]');
  
  // check we're getting the correct info
  console.log("[" + name + "]:", el.value);
  
  // save it to storage (you may also want to retrieve the last value and append it)
  window.localStorage.setItem(name, el.value);
}
input {display: block; margin: 0 0 1em; } pre { font-size: 0.9em; display: block; margin: 0.5em 0; }
<script>console.log = function () { document.getElementById("output").innerHTML = Array.prototype.slice.call(arguments).join(" "); }</script>
<textarea name="textbox" cols="50" rows="3">
say it...
</textarea>
<input type="submit" onclick="appendToStorage('textbox')"/>
<textarea name="textbox-again" cols="50" rows="3">
say it again...
</textarea><br>
<input type="submit" onclick="appendToStorage('textbox-again')"/>
<pre id="output"></pre>

Note: The above doesn't reflect best practice, however it does show how to retrieve a value from your textfield.

som
  • 2,023
  • 30
  • 37