0

2 text fields and a button. One text field will take the name and the other a phone number.The button will save the entry into the localstorage as a json array.

how to do this in html5 ?

  • 1
    Searching on Google and StackOverflow? http://stackoverflow.com/questions/2010892/storing-objects-in-html5-localstorage or http://stackoverflow.com/questions/3357553/how-to-store-an-array-in-localstorage – Getz Dec 24 '13 at 09:27

5 Answers5

1

Try this,

    // Call this function on button Click
    function saveDataInLS(){
    var obj={};
        obj.name=document.getElementById('name').value;
        obj.phone=document.getElementById('phone').value;

    var listObj=localStorage.getItem('DATA');
    if(listObj!=null){
      listObj=JSON.parse(listObj); //this will give array of object
      listObj.push(obj);
    }else{
      listObj=[obj]; //first time 
    }
   // Save Data in Local Storage 
    localStorage.setItem('DATA',JSON.stringify(listObj)); 
   //Please check Local Storage which will be like
    //[{"name":"Anand","phone":"6546456456"}{"name":"Andy","phone":"78688"}]
}

To get Data From Local Storage use,

var dataArr= localStorage.getItem('DATA');
    dataArr=JSON.parse(dataArr);//this Will return An JS Array 

   dataArr[0]['name']//to get Name for first index(i==0)
   dataArr[0]['phone']//get contact number  for first index(i==0)

Working New Demo

Anand Jha
  • 10,404
  • 6
  • 25
  • 28
0

Try this

var urarr = { 'date': 1, 'phn_num': 2};

// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(urarr));

// Retrieve the object from storage
var getObject = localStorage.getItem('urarr');

console.log('getObject: ', JSON.parse(getObject));
Sridhar R
  • 20,190
  • 6
  • 38
  • 35
0
var texFieldName="abc"
var textFiledNumber="num"
var json={
"name":textFieldName,
"number":textFiledNumber
};
localStorage.setItem("data",json);
nation best
  • 196
  • 8
0

You should convert JSON to string and add event listener (with jQuery probably) on button click:

$('#button').click(function(e) {
    var json = {};
    json.tel = $('#tel').val();
    json.name = $('#name').val();
    localStorage.setItem('object', JSON.stringify(json));
});
// get Item
var jsonParse = JSON.parse(localStorage.getItem('object'));
Yurii Kovalenko
  • 419
  • 3
  • 10
0
$('#three').click(function () {

    localStorage.data = JSON.stringify($('form').serializeArray());
    console.log(localStorage.data);
});

<form>
    <input type='text' name='one' id='one' />
    <input type='text' name='two' id='two' />
    <input type='submit' id='three' />
</form>

Working Demo

underscore
  • 6,495
  • 6
  • 39
  • 78