How to save changes to a list after reloading

- 1 answer

Ad

I am making a simple list and each time the user enters writes something in a form, it gets added to an unordered list. However once the page is reloaded, the li disappears. I've read something about local storage to solve this problem but i have no idea how to use it or even if that is the right solution. I don't know if it'll help but here is my code.

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" type="text/css" target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="script.js"></script>   
<script src="http://use.edgefonts.net/lato:n9,i4,n1,i7,i9,n7,i1,i3,n4,n3:all.js"></script>
</head>
<body>
<form>
<input type = 'text' name = 'to do' value = 'Write Here' class= 'input'>

</input>
</form>
<button type='button' class= "d">Enter</button>
<ul></ul>
</body>
</html>

body{
background-color: #eae4dd
}

form {
position: relative;
width: 20em;
height: auto
}

.input {
width: 20em;
margin: auto;
position: absolute;
font-size: 1.5em
}

button {
position: relative;
cursor: pointer;
left: 24em;
top: .05em;
font-size: 1.3em;
background-color: #ceecfc;
border-color: #bff0f2;
color: #0a1417
}

ul {
list-style-type: none;
}

li {

margin-top: .2em;
font-size: 2em;
margin-left: -1.3em;
padding-left: .5em;
background-color: rgb(95, 147, 170);
font-family: lato;
color: #baecf2;
border-radius: .5em
} 

$(document).ready(function(){
$("button").click(function(){
    var input = $('input').val();
    $("ul").append("<li>" + input + "</li>");
});
});
Ad

Answer

Ad

Yep, you can use localStorage pretty easily for this! Make your javascript look something like this

//This will set the list HTML if it exists in localstorage
if (localStorage.listHTML) {
  $("ul").html(localStorage.listHTML);
}

$("button").click(function() {
  var input = $('input').val();
  $("ul").append("<li>" + input + "</li>");
  //This will update the value that is in localStorage when you add a new item
  localStorage.listHTML = $("ul").html();
});

You could even add a button to reset the localStorage on click.

$("#reset").click(function() {
  $("ul").html("");
  localStorage.listHTML = "";
});

Full example on JSFiddle

More info on localStorage

Ad
source: stackoverflow.com
Ad