tags:

views:

20

answers:

2

I'm new to jQuery, and I'm trying to cause another identical dropdown menu to appear each time the user presses a button. I thought this would work, where #append is the button id and #foo is the dropdown id:

<script type="text/javascript">
$(document).ready(function(){
$("#append").click(function(){
$("#foo").append($("#foo"));
});
});
</script>

However, rather than duplicating the original dropdown, it causes it to disappear! What am I doing wrong?

+2  A: 

You want something like this:

$(document).ready(function(){
  $("#append").click(function(){
  $("#foo").parent().append($("#foo").clone().removeAttr("id"));
  });
});

.append() adds to the end of the element it was called on, so in this case you want to append to the parent, not inside the <select> element (like you would to add options). Also, you want to .clone() it unless you want to move the original instance. Also make sure your IDs are unique, I'd remove the id="foo" and give it a class, or remove the ID on copies, etc...anything but duplicate IDs.

Nick Craver
Got it, thanks!
paracaudex
+1  A: 

If you want to duplicate an element use clone():

$("#foo").clone().attr("id", "foo2").insertAfter("#foo");

That being said, don't try and create your own menu. Use an existing plugin (there are many eg superfish). Menus have notorious cross-browser issues. There is no value in reinventing that particular wheel.

cletus