javascriptjqueryjquery-data

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?


Solution

  • 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.