I have a form which saves a users preferance in local storage, it can be seen in this fiddle or below.
With what I have so far there are 2 main problems.
- On clicking the save button you are meant to empty the myStorage then append what you have just selected in there, so they can see the live result of what they have clicked. It only remembers if you re-run the fiddle.
My biggest problem is that what I have is great for select fields with one option but in this case the user can select multiple, so what do I need to add to it so that the user can save multiple values to local storage so next time they load the page there multiple selections will be saved?
<form name="Filter"> <select multiple="1" id="filter"> <option value="111">Andrew</option> <option value="222">Bill</option> <option value="333">Charles</option> <option value="444">Dikembe</option> <option value="555">Edward</option> </select> </form> <div id="store">click to store</div> <br> <h3>People I have stored</h3> <div id="myStorage"></div>
JS
var iSelectedTitle = localStorage.getItem('title');
var iSelectedVal = localStorage.getItem('value');
console.log("iSelectedTitle: " + iSelectedTitle);
console.log("iSelectedVal: " + iSelectedVal);
$("#filter option").each(function () {
if ($(this).val() == iSelectedVal) {
$(this).attr("selected", "selected");
}
});
$("#store").click(function () {
var mytitle = $("#filter option:selected").text();
var storedTitle = localStorage.setItem("title", mytitle);
console.log("mytitle: " + mytitle);
console.log("storedTitle: " + storedTitle);
var myValue = $("#filter option:selected").val();
var storedValue = localStorage.setItem("value", myValue);
console.log("myValue: " + myValue);
console.log("storedValue: " + storedValue);
if (iSelectedTitle != "undefined") {
$('#myStorage').empty().append(iSelectedTitle);
}
});
if (iSelectedTitle != "undefined") {
$('#myStorage').append(iSelectedTitle + ' - <a target= "_blank "href="http://www.example.com/' + iSelectedVal + '">View profile</a>');
}
You could save multiple values in an array,
The array would need to be serialized before it is saved to
localStorage
Likewise, the stored data will have to be unserialized after it is read back
You can add multiple options to an array using
map
of jQuery :This will give you a nice array like this :
For adding to localStorage :
For refreshing the
myStorage
container with your newly added people, you'll have to call this handler as the last event inside the `click event (above).Then, in
DOM ready
, callgetFromStore
to refreshmyContainer
on load of the page:Demo : http://jsfiddle.net/hungerpain/hqVGS/9/
EDIT
To select the checkboxes by default, add the folowing line in the
getFromStore
function :Updated demo : http://jsfiddle.net/hungerpain/hqVGS/10/