Using Localstorage In Html5
Solution 1:
It prints the value for team 1 a ton of times over and over. The 2nd click and on seem to be working
That's because the localStorage
object is persistent. Even when the source code of your script changes, the localStorage
values will still exist. You might be confusing localStorage
with sessionStorage
.
Fixing your code:
- Fix the syntax error by placing a
);
after the last}
. typeof
is not a function, please do not make it look like one, by removing the parentheses.- The very first time, nothing will print, because you're adding a space instead of the value of Team1.
- Instead of setting the property directly, it is recommended to use the
.getItem
and.setItem
methods, to avoid mistakes as using conflicting key names. - Your current "list" is a set of a concatenated string. That's not easily maintainable. Either use an unique separator to separate your values, or use
JSON.stringify
andJSON.parse
to store real arrays.
Demo: http://jsfiddle.net/BXSGj/
Code (using JSON):
$('#dostuff').click(function(e) {
e.preventDefault(); // Prevent the form from submittingvar team1 = $('input[name="Team1"]').val();
if (typeofStorage !== "undefined") {
// Will always show an array:var teamlist = JSON.parse(localStorage.getItem('teamlist') || '[]');
teamlist.push(team1);
localStorage.setItem('teamlist', JSON.stringify(teamlist));
$('#nicteamcolumn').html("Team:<br>" + teamlist.join('<br>') + "<br>");
}
});
Using a separator (only showing different lines):
varSEP = '|'; // Separator examplevar teamlist = (localStorage.getItem('teamlist') || '').split(SEP);
teamlist.push(team1); // Still the samelocalStorage.setItem('teamlist', teamlist.join(SEP));
To remove the stored items, use the localStorage.removeItem
method:
localStorage.removeItem('teamlist');
See also: Compability table for the Storage
object.
Post a Comment for "Using Localstorage In Html5"