wyc
wyc

Reputation: 55283

How to copy these list element to another list using jQuery?

Let's say I have list elements (more than one) like these:

<li id="menu-item-51604"><span class="dish-name">葡萄柚清心優多</span><span class="dish-price">25/35/50</span><span class="dish-description"></span><span class="dish-notes"></span></li>

<li id="menu-item-3144"><span class="dish-name">清心優多</span><span class="dish-price">25</span><span class="dish-description"></span><span class="dish-notes"></span></li>

<li id="menu-item-2154"><span class="dish-name">柚清心優多</span><span class="dish-price">35/50</span><span class="dish-description"></span><span class="dish-notes"></span></li>

I want to be able to copy the list element that I click to a list called ul.check-items.

Any suggestions to accomplish this?

Upvotes: 0

Views: 260

Answers (2)

nnnnnn
nnnnnn

Reputation: 150050

Well something like this would put a click handler on that li item specifically:

$("#menu-item-51604").click(function() {
   $("ul.check-items").append( $(this).clone() );
});

But presumably you want similar behaviour from every element in whatever list "menu-item_51604" belongs to, so try so:

$("#yourULidHere li").click(function() {
   $("ul.check-items").append( $(this).clone() );
});

Note that this will result in multiple elements with the same id, so really you should change or remove the id from the copy:

$("ul.check-items").append( $(this).clone().removeAttr("id") );
// OR
$("ul.check-items").append(
     $(this).clone().attr("id", function(i,oldVal) { return oldVal + "copy"; })
);

(That last line will also create multiple elements with the same "...copy" id if you keep clicking the same element, but it shows you one way to modify the id...)

Upvotes: 0

j08691
j08691

Reputation: 207900

Try this:

$('#menu-item-51604').click(function(){
    $(this).clone().removeAttr("id").appendTo('ul.check-items');
});

Based on your edited post:

$('#firstlist li').click(function(){
    $(this).clone().removeAttr("id").appendTo('ul.check-items');
});

where firstlist is the id of the list that you want to clone from.

Upvotes: 2

Related Questions