is there a way to use localstorage on the code below? just to make sure that the text you typed remains on the box you sent it to even after refreshing.
jquery:
$(document).ready(function() {
var $input1 = $('.textField');
$(".sendTo").on("click", function() {
var box = $(this).data("sendto");
$(`[data-box='${box}']`).append($input1.val());
$input1.val("");
});
});
html:
<input class="textField" type="text">
<div class="sendTo" data-sendto='box1'>send to box 1</div>
<div class="sendTo" data-sendto='box2'>send to box 2</div>
<div data-box="box1">box 1</div>
<div data-box="box2">box 2</div>
im having trouble where to place the localStorage.setItem
andlocalStorage.getItem
2
Answers
You can achieve it like this (see comments for more explanation):
You can also save the data on every keypress if you add this event registration on the input-field:
To use this code with localstorage.setItem / getItem you just need to know the key to read. That’s already passed in the box variable:
so you can use it as:
To retrieve with
getItem
you can loop each output that has attribute[data-box]
, get the.data("box")
and use that as the key:Updated code:
Note: stackoverflow snippets don’t allow localstorage, so you can use this fiddle to see it in action: https://jsfiddle.net/35ugqf6j/
Note: this clears the default "box 1" text in the outputs – you can check for
null
if you don’t want that on the first run.Note: you’ll need a method to clear the output/localstorage otherwise it just gets bigger and bigger.