localStorage - Multiple Values

962 Views Asked by At

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>

http://jsfiddle.net/w3uu6y0r/1/

2

There are 2 best solutions below

0
On BEST ANSWER

The mail part is pretty simple. Replace the mail variable in your click handler to just grab the value:

obj.push({"id":  id, "mail":$('#mail').val()});

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?

if (obj.length > 0) {
        id = Math.max.apply(null, obj.map(function (entry) { return parseFloat(entry.id); })) + 1;
    }
    else {
        id = 1;
    }

Okay let me explain this code.

obj.map(function (entry) { return parseFloat(entry.id); })

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]);

3
On

You can check the number of objects in the localStorage and increment the id every time (plus 1, if you want the id to start from 1).

$(".store").on("click", function () {
    var mailaddress = localStorage.getItem("mailaddress");
    var obj = [];
    if (mailaddress) {
        obj = JSON.parse(mailaddress);
    }
    var id = obj.length + 1; // increment the id
    var mail = $('#mail').val(); // get the textbox value
    obj.push({ // push it to obj
        "id": id,
        "mail": mail
    });
    localStorage.setItem("mailaddress", JSON.stringify(obj));
});

Fiddle: http://jsfiddle.net/w3uu6y0r/3/