简体   繁体   中英

store the localstorage value in the form of json

Hi I am trying to save some input[type="text"] and input[type="hidden"] values in local storage. Below is the JS:

$('.proceed_btn').on('click', function(){

    $('input[type="text"]').each(function(){    
      var id = $(this).attr('id');
      var value = $(this).val();
      localStorage.setItem(id, value);
    }); 
    $('input[type="hidden"]').each(function(){    
      var id = $(this).attr('id');
      var value = $(this).val();
      localStorage.setItem(id, value);
    }); 

});

The value are getting stored perfectly. But I want to store these value in json format. But how to save both these values in one variable. For example:

order: {
   id: '', 
   product: '',
   service: '',
   name: ''
} 

I have checked the JSON stringify but how to implement with different types of input together

Simply build an object and then stringify it. For instance, if I assume the name of your input elements is the name you want to use on your object:

$('.proceed_btn').on('click', function(){
    // Blank to start with
    var order = {};

    // Loop through all inputs...
    $('input[type="text"], input[type="text"]').each(function(){
      // ...adding their values as properties
      order[this.name] = this.value;
    }); 

    // Store that object in JSON format
    localStorage.setItem("order", JSON.stringify(order));
});

Later if you want to retrieve it and set the inputs based on its values:

var order = JSON.parse(localStorage.getItem("order") || "null");
if (order) {
    $('input[type="text"], input[type="text"]').each(function(){
        if (this.name in order) {
            this.value = order[this.name];
        } else {
            this.value = "";
        }
    });
}

There are only 2 parameters will be there while writing localstorage:

ex. localStorage.setItem( 'car', car ); 1st parameter is key actually and 2nd parameter is value;

You have passed 3 paramters which is wrong.

If you can to store multiple values in localstorage, create object of that values and write that object to localstorage:

ex.

var car = {};
car.wheels = 4;
car.doors = 2;
car.sound = 'vroom';
car.name = 'Lightning McQueen';
console.log( car );
localStorage.setItem('car', JSON.stringify(car));
console.log( JSON.parse( localStorage.getItem( 'car' ) ) );

I think this will help.

var objectToSave = {};
$('.proceed_btn').on('click', function(){

$('input[type="text"],input[type="hidden"]').each(function(){
  var elem = $(this);
  var id = elem.attr('id');
  var value = elem.val();
  objectToSave[id] = value;
}); 
  localStorage.setItem('order', JSON.stringify(objectToSave));
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM