Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery clone multiple instances why

Tags:

jquery

clone

hope can help, trying out Jquery clone which seems to work, but I get "multiple" clones not single clones on "repressing" the button.

e.g.: I want to clone this :

echo '<select class="hello">';
    foreach ($pageposts as $post):
    echo '<option>'.$post->post_title.'</option>';
    endforeach;
    echo '</select>';

on click of this

echo '<input type="button" id="rp" value="add">';

Yes from WordPress and Yes the "hello" class is from the JQuery pages

My JQuery function is:

$j=jQuery.noConflict();
$j(document).ready(function() {
$j('#rp').click(function(){ 
$j('.hello').clone().appendTo('#goodbye');
});
});

So my "overall code snippit" looks like this:

echo '<select class="hello">';
foreach ($pageposts as $post):
echo '<option>'.$post->post_title.'</option>';
endforeach;
echo '</select>';
echo '<div id="goodbye"></div>';
echo '<input type="button" id="rp" value="add">';

I clone "once" on the first press, but then it goes in multiples i.e.:

1 click gives 1 clone plus 1 original - what I want

2 clicks gives 3 clones plus 1 original - not what I want I want 1 original plus 2

3 clicks gives 7 clones plus 1 original - not what I want I want 1 original plus 3 etc.

Suggestions please. Thanks

like image 369
user351657 Avatar asked Feb 05 '26 18:02

user351657


1 Answers

It's because your selector is looking for a class:

$j('.hello')

Everytime you clone and append this to another element you're adding yet another .hello element, therefore your cloning every single .hello element it can find.

Perhaps you should remove the class name when it's been cloned:

$j('.hello').clone().removeClass('hello').appendTo('#goodbye');

Or perhaps even change it:

$j('.hello').clone().removeClass('hello').addClass('cloned_hello').appendTo('#goodbye');

You might want to add a different class so your CSS will still work, but ultimately this is why you're getting multiple cloned items.

like image 160
Ben Everard Avatar answered Feb 07 '26 13:02

Ben Everard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!