I am trying to create a small web app that will allow users to create a list of movies they want to see. So far, I’ve been able to get the list to be sortable and I’ve implemented the ability to add divs to the list. I’ve also been able to use localStorage to save the first div, but not the rest. The rest are clones of the first.
My JS:
$(document).ready(function(){
$("#movie-list").sortable({
handle : '.handle',
update : function(){
var order = $("movie-list").sortable('serialize');
}
});
$("#add").click(function(){
$(".movie").last().clone(true).insertAfter($(".movie").last());
});
$("#save").click(function(){
var titles = $(".title").html();
var divs = $(".movie").html();
localStorage.setItem("UserTitles", titles);
localStorage.setItem("divs", divs);
alert("Your list has been saved!");
});
$(function(){
if (localStorage.getItem("UserTitles")){
var titles = localStorage.getItem("UserTitles")
}
else if (localStorage.getItem("divs")){
var divs = localStorage.getItem("divs")
}
else{
var titles = "New Movie";
var divs = $(".movie").html();
}
$(".title").html(titles);
});
});
My HTML:
<body>
<div id="header">MY MOVIE LIST</div>
<div id="movie-list">
<div class="movie">
<img src="http://aux4.iconpedia.net/uploads/74429410244335194.png" width="16" height="16" class="handle" alt="Move" />
<label class="title" contenteditable="true"></label>
</div>
</div>
<div id="savelist">
<img id="save" src="savelist.png" />
</div>
<div id="addmovie">
<img id="add" src="addmovie.png" />
</div>
</body>
Ideally, I want the user to press the “Save” button and have the divs that exist, their order, and their contents saved using localStorage.
Calling
$(".movie").html()will only give you the html for the first element found of the class movie. Instead, you want to use theeachmethod to iterate over each element found. This can be done with the following:You can find additional documentation at http://api.jquery.com/each/.
Update
I reworked your ready function a bit to save the entire movie list and then reload it.
I found two issues with your code. One, your
localStorage.getItem("UserTitles")call was blocking the call tolocalStorage.getItem("divs")since you used anelse if. Two, when you check for thelocalStorage.getItemvalues you need to check them againstnull. I also made a small change by storing the entire contents of themovie-listdiv inlocalStorage.