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>
Firstly
idattributes must be unique within a document, so you should remove theidproperties from theinputelements within.card(or make them unique). Secondly your fiddle example did not include jQuery.To fix your actual issue you can retrieve the parent
.cardfrom theinputusingclosest(). You can thenappend()this to the requireddivby checking which one it is currently contained in, something like this: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 outdatedon*event attributes. As you had already included jQuery code, I used that to achieve this.