2

Hy, my problem is this http://jsfiddle.net/VZ2MK/1/

(function(){

    var input = $('.test').clone();

    $('a.add_input').on('click', function(e){

        $(this).before(input);

        e.preventDefault();

    });

})();

I need to add dynamically some parts of a form, and i thought i'll clone it and then add it. And it worked for the first time, but if i want to add more than once, it stops, i mean it doesn't work. Any ideas?

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
Mr. Sam
  • 790
  • 2
  • 9
  • 31

4 Answers4

6

You should clone it by every click. The demo.

var input = $('.test');

$('a.add_input').on('click', function(e){
    $(this).before(input.clone());

    e.preventDefault();

});
xdazz
  • 158,678
  • 38
  • 247
  • 274
5

The problem is that before detatches the element from where it currently is, before inserting it before the selected element. You need to do the clone each time, rather than doing it once:

(function(){
    $('a.add_input').on('click', function(e){
        var input = $('.test').last().clone();    

        $(this).before(input);

        e.preventDefault();
    });
})();

Your original code inserted the clone the first time, but on subsequent occasions removed it before re-adding it in exactly the same place.

Note that I am only cloning the last of the $('.test') items to avoid adding 1 the first time, 2 the second time, 4 the third time, etc.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
0

Cloning every click works:

(function(){
    $('a.add_input').on('click', function(e){
var input = $('.test').clone();
        $(this).before(input);

        e.preventDefault();

    });  
})();
Sammaye
  • 43,242
  • 7
  • 104
  • 146
-2

This should work:

http://jsfiddle.net/VZ2MK/4/

But I didn't use clone()

 (function(){
     input = $('.test').html();   
     $('a.add_input').click(function(e){   
         $(this).before('<div>' + input + '</div>');       
         e.preventDefault();      
     });   
 })();
Control Freak
  • 12,965
  • 30
  • 94
  • 145
  • This is a bad answer. It destroys any data or event handlers stored on the elements. [This answer](http://stackoverflow.com/a/7393126/417562) to another question explains why this is a bad technique. – lonesomeday Jun 27 '12 at 08:21
  • Maybe the op was looking for this instead.. ? – Control Freak Jun 27 '12 at 08:23