![Creative 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);
})
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.
wow, thank you a lot
– Rouzy
6 hours ago