Search code examples
jqueryclone

jQuery on click clone and remove original


I run into a bit of a trouble, and I'm not sure how to make this work.

I have 3 radio buttons, two of them will perform an action. When user clicks on artist, or song radio, I need to clone and append object from one section to another. Here is my code:

<input tabindex="0" name="set" value="album" type="radio">
<div class="wrap">
  <input tabindex="0" name="set" value="artist" type="radio" checked="checked">
  <div class="company"> ...... </div>
</div>
<div class="wrap">
  <input tabindex="0" name="set" value="song" type="radio">
</div>

and here is js:

$("input[name=set]").change(function () {
    if($(this).val() == "artist" || $(this).val() == "song") {
        var $wrap = $(this).closest(".wrap");
        $(".company").clone(true).appendTo($wrap);

        here remove the original $('.company') object
    }

});

The idea is that either artist or song radio will have the same functionality, and each of them will have .company object appended only ones, but removed from the other and vice versa


Solution

  • Just use appendTo() no need for clone(), it will move the dom element

    $("input[name=set]").change(function () {
        if($(this).val() == "artist" || $(this).val() == "song") {
            var $wrap = $(this).closest(".wrap");
            $(".company").appendTo($wrap);
        }
    });