JQuery.data keeps data from last element only
I am trying to use jQuery.data () and store the object in my HTML elements. Every time I add a list item to my unordered list, it only stores the last object in the specific li-Element. All other saved li-Elements data is discarded!
I have built a small example. JSBin-Example
On the left, I create a list with the object saved by it. On the right, I'm trying to show data related to an object.
Why does it only display the object associated with the last HTML element?
Working Example:
JSBin-Example
source to share
This is because you are modifying the property innerHTML
of the wrapper element. What happens is, in each iteration, the items are restored, the current items are deleted, and the new items have no data saved. Using a property innerHTML
is the worst way to change the content of an element. You just need to create an element li
and add it to the wrapper element:
var random = 0;
// var testObject = [];
function addNewItem(){
random += 1;
var id = "testId" + random;
var text = "This is my " + random + ". text";
var data = {id: id, text: text};
// testObject.push(data);
// You can pass an object as the second argument
// to jQuery constructor and it calls the
// corresponding methods as setter
$('<li></li>', {
text: text + JSON.stringify(data),
id: id,
data: data
}).appendTo('#listId');
}
// bind and trigger click event
$("#add").on('click', addNewItem).click();
source to share
I changed
for(var i = 0; i < testObject.length; i++){
var listItem = "";
var id = testObject[i].id;
listItem += liStart + id + liStart2;
listItem += testObject[i].text;
listItem += liEnd;
unorderedList.innerHTML += listItem;
$("#"+id).data(testObject[i]);
}
to this in your updatelist function
//for(var i = 0; i < testObject.length; i++){
var id = testObject[testObject.length-1].id;
listItems += liStart + id+"savedData" + liStart2;
listItems += JSON.stringify($("#"+id).data());
listItems += liEnd;
//}
savedData.innerHTML += listItems;
and it fixed the problem
source to share
To help you understand my comment on the question, I thought it would be best if I give an example of what I mean.
I didn't have enough time to go through the solution completely, but I wanted to give an example of what I would call more readable code.
I added all the variables at the top of the function. This will allow you to read and find items much faster if you need to change them.
I have also concatenated a lot of string values โโthat you had in an object, namely an element li
.
I've never used $ .data () as an object before, so I didn't know how I can use it to set values โโto updateSavedData()
$('li')
, although it console.log()
shows the correct key / values.
$(document).ready(function(){
var uID = 0;
var testObject = [];
var unorderedList = $("#listId");
var savedList = $("#savedData");
var TOL = 0; //TestObjectLength
var textTemplate = "This is my [0] text!";
function addNewItem(){
uID++;
testObject.push({id: uID, text: textTemplate.replace("[0]", uID)});
TOL = testObject.length-1;
updateList();
}
function updateList(){
var li = $('<li>', { id: testObject[TOL].id, data: testObject[TOL], text: testObject[TOL].text });
li.appendTo(unorderedList);
updateSavedData(li.data());
}
function updateSavedData(li){
console.log(JSON.stringify(li));
$('<li>', JSON.stringify(li)).appendTo(savedList);
}
addNewItem();
$("#add").on('click', addNewItem);
});
Working example
http://jsbin.com/ralizazahe/1/edit?js,console,output
Anyone who wants to progress down this path, do as I would like to see how this can be achieved.
Update
Took one more step and edited this
$(document).ready(function(){
var $displayList = $("#listId");
var $savedList = $("#savedData");
var textTemplate = "This is my {0} text!";
var uID = 0; //Unique ID
var data = { id: null, text: null }; //Gives a reference
function init(){
uID++;
data = { id: uID, text: textTemplate.replace("{0}", uID) };
}
function addNewItem(){
init();
$('<li>', data).appendTo($displayList);
updateSavedData(data);
}
function updateSavedData(li){
$('<li>', li).appendTo($savedList);
}
addNewItem();
$("#add").on('click', addNewItem);
});
source to share