Kristiyan Kostadinov
Kristiyan Kostadinov

Reputation: 3712

jQuery .data() append

So this is my scenario: I have a few questions that the user answers and I want to store them so at the end of the questionnaire I can render a list of each question and the answer. Obviously I could go with a global variable but the problem is that there are other questionnaires on the site. My solution is to go with jQuery's .data(). My problem is that when I try to add similar data, it overwrites the previous. Here's a simple example:

<div id="test"></div>

$("#test").data({name:"foo",answer:"bar"});
$("#test").data({name:"john",answer:"doe"});

console.log($("#test").data()); //logs name:"john",answer:"doe"

How can I get it to keep both values?

Upvotes: 0

Views: 3122

Answers (3)

MartinCzerwinski
MartinCzerwinski

Reputation: 1

I think this is the simplest solution to appending new data:

  • First get the data from the element,
  • store it in a variable,
  • append your new data,
  • and then re-add the data to the element
    var myData = [];

    //get your existing data
    myData.push($("#testID").data());

    //append your new data
    myData.push({fname:"john",lname:"doe"});

    //update element
    $("#testID").data(myData);

Upvotes: 0

Adil
Adil

Reputation: 148110

You are over writing the previous data, add both record in single call in array.

Live Demo

$("#test").data([{name:"foo",answer:"bar"}, {name:"john",answer:"doe"}]);

Access data like array,

alert($("#test").data()[0].name);
alert($("#test").data()[1].name);

Edit based on comments, if you want to add records to data one after other you can use key value pair.

Live Demo

$("#test").data("1", {name:"foo",answer:"bar"});
$("#test").data("2", {name:"john",answer:"doe"});

As @Heart pointed out if this data is important then storing on client is open for client and could be modified. Using ssl and posting it as you get it from user could save from data security being compormised.

Upvotes: 2

krishwader
krishwader

Reputation: 11371

Why dont you try adding them in with a key?

$("#test").data("Answer1", {
    name: "foo",
    answer: "bar"
});
$("#test").data("Answer2", {
    name: "john",
    answer: "doe"
});

console.log($("#test").data());
/*
//Console Output
 [object Object] {
   Answer1: [object Object] {
     answer: "bar",
     name: "foo"
   },
   Answer2: [object Object] {
     answer: "doe",
     name: "john"
   }
  }
*/

This way your objects would be unique.

Demo : http://jsbin.com/ixuqal/1/edit

Upvotes: 1

Related Questions