1

On my page I want to duplicate a select element when a user clicks on the ADD button. I have this code below, which you can also see on this jsfiddle.

<select id="sel">
    <option>1</option>
    <option>2</option>
</select>
<button id="add">ADD</button>
<div id="test"></div>
<script>
var copy = $('#sel').clone().attr('id', '');

$('#add').click(function(){
    $('#test').append(copy);    
});
</script>

The code should add an equivalent amount of select elements as the user has clicked the ADD button. But it only adds one select and seems to be overwriting the initially appended one after the first click of the ADD button.

What am I doing wrong?

AtheistP3ace
  • 9,611
  • 12
  • 43
  • 43
Timo002
  • 3,138
  • 4
  • 40
  • 65
  • OK, but offcourse there was a reason why I first cloned it so I could add it later. This is because I use select2(). So I need to the 'raw' select. See this JSfiddle: https://jsfiddle.net/ma65yuvd/6/ – Timo002 Nov 10 '15 at 21:10

3 Answers3

0

You want to clone a new one every time they click not just once:

$('#add').click(function(){
    var copy = $('#sel').clone().attr('id', '');
    $('#test').append(copy);    
});

Fiddle: https://jsfiddle.net/ma65yuvd/3/

AtheistP3ace
  • 9,611
  • 12
  • 43
  • 43
0
// Clones element, creating new element, call it "ElementB"
var copy = $('#sel').clone().attr('id', '');

// Every time you click "add"
$('#add').click(function(){

    // Append "ElementB" to "#test"
    $('#test').append(copy);    
});

In other words, you are only creating one DOM element. The first .append will move that element to #test. The .append calls after that will also move it to #test, which will result in no net changes.

A simple fix is to call .clone each time:

var original = $('#sel');

$('#add').click(function(){
    // Now a new element is created for each click!
    var copy = original.clone().attr('id', '');
    $('#test').append(copy);    
});
Stryner
  • 7,288
  • 3
  • 18
  • 18
  • I replied to my own post. There was a reason why I cloned it in a variable. I need the raw select 'html' to copy multiple times. – Timo002 Nov 10 '15 at 21:11
  • @Timo002 That should be specified in the question itself, because it changes the premise. In that case, instead of cloning it, I would suggest [getting the `outerHtml`](http://stackoverflow.com/questions/2419749/get-selected-elements-outer-html#answer-10405571) and appending that. – Stryner Nov 10 '15 at 21:21
0

You have to move the clone inside the click event!

<select id="sel">
    <option>1</option>
    <option>2</option>
</select>
<button id="add">ADD</button>
<div id="test"></div>
<script>

$('#add').click(function(){
    var copy = $('#sel').clone().attr('id', '');
    $('#test').append(copy);    
});
</script>
Marcus Abrahão
  • 696
  • 1
  • 8
  • 18
  • I replied to my own post. There was a reason why I cloned it in a variable. I need the raw select 'html' to copy multiple times. – Timo002 Nov 10 '15 at 21:11