I have got two set of lists once complete and one incomplete… If I click on the complete line item, it should be transferred to the incomplete list (prepend) and vice versa.
The code is real simple I am using basically similar code to transfer from incomplete to complete and complete to incomplete.
The incomplete to complete list transfer works.
The complete to incomplete transfer doesn’t. (the cloning process doesn’t seem to carry through.. It does clone the object makes the change to the cloned object but when I need it to prepend the cloned object to the incomplete list id it doesn’t do it.
https://jsfiddle.net/35nbpefz/2/
$("body").on("click", ".incompletetasklist", function () {
var id=$(this).attr('id');
var incomp_task=$(this).clone().addClass('completetasklist').addClass('bg-infolight').removeClass('incompletetasklist');
$('#quicktaskcomplete').prepend(incomp_task);
$("#"+id).remove();
});
// complete task to incomplete task
$("body").on("click", ".completetasklist", function () {
//console.log($(this).attr('id'));
var id=$(this).attr('id');
var comp_task=$(this).clone().addClass('incompletetasklist').removeClass('bg-infolight').removeClass('completetasklist');
//var comp_task=$(this).clone();
//console.log(comp_task);
$('#quicktaskincomplete').prepend(comp_task);
$("#"+id).remove();
});
I created a jsfiddle… I know this must be something so simple but I cannot see it . I have tried prependTo
which has an entirely different result. Not too sure what I am doing wrong. It is literally the same code… what am I doing wrong ?
I also noticed that if I interchanged the incomplete div position with the completed div position the second clone function works… but now the first clone function doesnt work… I hope I am making sense here.
2
Answers
The culprit in your code is removing the link after pre-pending it to another list.
The reason is simple: when the same
id
occurs twice then always the latest one got affected. so$("#"+id).remove();
always removed the pre-pend link only.Solution: Instaed of
$("#"+id).remove();
do$(this).remove();
working snippet:
Another way using
data-attributes
and single event handler code: https://jsfiddle.net/6bfetqka/You’re having multiple items with the same id, this causes problems. You should move the id’s to a data-attribute or generate new id’s when they’re needed.
Another (much simpler) option is to not clone, but simply move the items:
This moves the items and sets the correct classes as well.