Jake Jake - 6 months ago 43
jQuery Question

Add/Remove parent div to another div by clicking button

I'd like the parent div ".card" of the button to be added to the blue div upon clicking the button, and also able to "returned" to the original red div upon clicking the button again.
jsfiddle

<div id="nonSelected">

<div class="card">
CARD #1
<input id="btnDefault" onclick="moveButton(this)" type="button" class="btn btn-default" value="ADD" />
</div>

<div class="card">
CARD #2
<input id="btnDefault" onclick="moveButton(this)" type="button" class="btn btn-default" value="ADD" />
</div>

</div>

<div id="selected">
</div>


<script>
function moveButton(elem){
if( $(elem).parent().attr("id") == "nonSelected" ){
$(elem).detach().appendTo('#selected');
}
else{
$(elem).detach().appendTo('#nonSelected');
}
}
</script>

Answer

Firstly id attributes must be unique within a document, so you should remove the id properties from the input elements within .card (or make them unique). Secondly your fiddle example did not include jQuery.

To fix your actual issue you can retrieve the parent .card from the input using closest(). You can then append() this to the required div by checking which one it is currently contained in, something like this:

$('.card input').click(function() {
    var $card = $(this).closest('.card')
    $card.appendTo($card.closest('#nonSelected').length ? '#selected' : '#nonSelected');
});

Updated fiddle

Note that you don't need to call detach() at all as the element is simply moved within the DOM. Also note that it's much better practice to use unobtrusive javascript to attach your event handlers instead of the clunky and outdated on* event attributes. As you had already included jQuery code, I used that to achieve this.