just a newbie using local storage. Can anyone help me with this problem?
My goal is when I click the Done button the input I've made is appending on the .sNote class however it's not appending the way I want to be. However, when I check my local storage the data I've input is there but not really append in my .sNote.
Can anyone help me? I'm really having a hard time using local storage cause my just new using this.
Please see this code and also you can see my actual code here https://codepen.io/rico-p-buenviaje/pen/yLXqQEB
$(document).ready(function() {
$(".aNote").on("click", function() {
var hrd = $(".iNote-items").val();
var para = $(".iNote-items-2").val();
console.log(hrd);
console.log(para);
if (hrd && para) {
localStorage.setItem(hrd, para);
}
});
for (var i = 0; i < localStorage.length; i++) {
localStorage.keys(hrd, para)[i]
$(".sNote").append(
'<div class="hrd">' + hrd[(localStorage.keys(hrd)[i])] +
'</div><div class="para">' + para[(localStorage.keys(para)[i])] + '</div>'
);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="iNote-inputs">
<textarea class="iNote-items" rows="3">aaaa</textarea>
<textarea class="iNote-items-2" rows="3"></textarea>
<div class="aNote">Done</div>
</div>
<div class="spl-hrd-iNote">
<div class="sNote"></div>
</div>
for (var i = 0; i < localStorage.length; i++) {
localStorage.key(i)
// localStorage.keys(hrd, para)[i]
$(".sNote").append(
'<div class="hrd">' +localStorage.key(i) +
'</div><div class="para">' + localStorage.getItem(localStorage.key(i)) +'</div>'
);
}
Try this. You haven't defined hrd anf para variables before the following line.
localStorage.keys(hrd, para)[i]
So that cause an error. and also that is not the proper way to read the localstorage. If you use localstorage for savin other data as well the best thing to use a separate localstorage item which contains an array of your storing items. That way you don't get unnecessary items in this iteration check Looping through localStorage in HTML5 and JavaScript for details
If you want to append this when click on 'done' button also better to move appending part to a function as below and call it in both cases.
function apendItem (key, value) {
$(".sNote").append(
'<div class="hrd">' + key+
'</div><div class="para">' + value + '</div>'
);
}
call above functions from click button as below
$(".aNote").on("click", function(){
var hrd = $(".iNote-items").val();
var para =$(".iNote-items-2").val();
if(hrd && para) {
localStorage.setItem(hrd, para);
apendItem (hrd, para);
}
});
call it onload as below
for (var i = 0; i < localStorage.length; i++) {
apendItem (localStorage.key(i), localStorage.getItem(localStorage.key(i)));
}