I have an input field named "mail". I want to add mailaddresses and ids into localstorage. The value for the mailaddress should come from the input field "mail" and the id should count up every time I add a mailaddress. At the moment there are static values for the vars "id" and "mail".
Can somebody give me a hint how I could do that?
Here is my code:
var id = 1;
var mail = "Mail";
$(".store").on("click", function(){
var mailaddress = localStorage.getItem("mailaddress");
var obj = [];
if(mailaddress){
obj= JSON.parse(mailaddress);
}
obj.push({"id": id, "mail":mail});
localStorage.setItem("mailaddress",JSON.stringify(obj));
});
$("#show").on("click", function(){
var item = JSON.parse(localStorage.getItem("mailaddress"));
alert(item);
console.log(item);
});
$('#reset').click(function(){
localStorage.clear();
});
<div id="storage">
<input type="text" id="mail" value=""/>
<button class="store">store</button>
<button id="reset">reset</button>
<button id="show">show</button></div>
The mail part is pretty simple. Replace the mail variable in your click handler to just grab the value:
You may want to do value & pattern checks on the entered email so you don't get junk.
For the id, you have an array of the ids already, so why not just grab the largest one and +1 it?
Okay let me explain this code.
Map is a function that iterates through an array, and returns a new array with the value from each return statement. So if you have an array of
[1,2,3]
and run[1,2,3].map(function(v) { return v + 1; });
you'll have[2,3,4]
. I'm using it in this case get an array of the ids. The parseFloat might be unnecessary, but i'm being cautious with local storage.Math.max can normally be used to return the highest number between two or more values:
Math.max(2, 5)
would return 5. In this case, i'm using apply so I can pass an array. It would be the same as:Math.max.apply(null, [2,5]);