Andrea Tulimiero Andrea Tulimiero - 5 months ago 14
jQuery Question

Jquery.prepend() removes last inserted value

I'm making a simple insertion with Jquery, and everything works fine
The only problem is that after the first insertion, the new object overwrites the last inserted one

function insert_note(note_data){
console.log(note_data);
var note_object = {}

note_data.forEach(function(item){
note_object[item.name] = item.value;
});

console.log(note_object);
note_layout = $(note_layout);
note_layout.find('span').text(note_object.note_title);
note_layout.find('p').text(note_object.note_content);
note_layout.attr('data-id', note_object.note_id);

$('#notes_container').prepend(note_layout);


And this is the note_layout saved in a js variable. Everytime I'm modifying it with the infos I get from the user and attach it to the DOM with prepend():

<div class="row" data-id="">
<div class="col l8 push-l2 s10 push-s1">
<div class="card blue-grey darken-1">
<div class="card-content white-text">
<span class="card-title"></span>
<p></p>
</div>
<div class="card-action">
<a class="waves-effect waves-teal btn-flat" data-action="set_as_done">Set as done</a>
<a class="waves-effect waves-teal btn-flat" data-action="postpone">Postpone</a>
</div>
</div>
</div>
</div>


Am I missing to consider something ?
Thx in advance !

Answer

As commented by A. Wolff, you are reusing the same note_layout after the first call, which is then moving the object, not creating a new one. You can fix this by never changing note_layout, and creating a new variable to hold the DOM object you are creating from it, and inserting that.

Change:

console.log(note_object);
note_layout = $(note_layout);
note_layout.find('span').text(note_object.note_title);
note_layout.find('p').text(note_object.note_content);
note_layout.attr('data-id', note_object.note_id);

$('#notes_container').prepend(note_layout);

to

console.log(note_object);
var note_layout2 = $(note_layout);
note_layout2.find('span').text(note_object.note_title);
note_layout2.find('p').text(note_object.note_content);
note_layout2.attr('data-id', note_object.note_id);

$('#notes_container').prepend(note_layout2);
Comments