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

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

2 Comments

the array is being overwritten...can u give me the code to display the items in the array as a list.
I have updated the answer please check it. hope this will help you to solve your problem :-)
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));

Comments

0
var texFieldName="abc"
var textFiledNumber="num"
var json={
"name":textFieldName,
"number":textFiledNumber
};
localStorage.setItem("data",json);

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.