localStorage + jQuery autosave and load p

The name of the picture


localStorage + jQuery autosave and load p



I have a code:


$(document).ready(function() {
var count = 1;

$("button").click(function() {
var inputVal = $('input').val();
$('div').append("<p>"+ inputVal +"</p>");
localStorage.setItem('pvalue'+count, inputVal);
$("input").replaceWith("<input id='num_" + count++ +"'/>");
})

var local = localStorage.getItem("pvalue"+ count);
$('div').append("<p>"+ local +"</p>");

})



This code saves all values of input but shows only first. I dont know how to display all saved p tags after refresh, can anybody help me?



HTML:


<body>
<div class='mt-5 text-center'>
<input> <button>Add</button>
</div>

<script src='script.js'></script>
</body>




1 Answer
1



The issue is due to your use of the count variable. This is fine when setting the data, however when re-loading it count will be set back to 1 and you won't explicitly know how many entries you've saved.


count


count


1



A much better idea would be to store an array in localStorage which you can easily add to and retrieve. Try this:


$(document).ready(function() {
$("button").click(function() {
var inputVal = $('input').val();
$('div').append("<p>" + inputVal + "</p>");

var pValues = JSON.parse(localStorage.getItem('pvalue')) || ;
pValues.push(inputVal);
localStorage.setItem('pvalue', JSON.stringify(pValues));
})

var pValues = JSON.parse(localStorage.getItem('pvalue')) || ;
var html = pValues.map(function(local) {
return '<p>' + local + '</p>';
}).join('');
$('div').append(html);
})





wow, thank you a lot
– Rouzy
6 hours ago





No problem, glad to help. If you need it, here's a working example in a fiddle as SO doesn't allow localStorage access in snippets: jsfiddle.net/RoryMcCrossan/8q6ewbgL
– Rory McCrossan
6 hours ago






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Keycloak server returning user_not_found error when user is already imported with LDAP

PHP parse/syntax errors; and how to solve them?

How to scale/resize CVPixelBufferRef in objective C, iOS