Doug Cassidy Doug Cassidy - 3 months ago 9
jQuery Question

Clone form elements, then wrap them in a div, then append?

I'm getting all the inputs from a form and cloning them into another form. This is working great (with the fix of jquery.fix.clone.js). I'm now simply trying to wrap the elements into a div, which isnt working because jquery always adds the other half of the tag, like

<div></div>


addbutt = $("form.prodform button.add");
addbutt.click(function(e){
e.preventDefault();
theform = $(this).closest('form');
$(theform).each(function(){
//lets validate,then we add
$('form#Receiver').append('<div class="appended">');
$('form#Receiver').append($(this).find('div.name') .clone());
$('form#Receiver').append($(this).find(':input').not(':button') .clone());
$('form#Receiver').append('<button>delete</button>');
$('form#Receiver').append('</div>');
});
})


I tried using html() to get the found inputs, but this just gets the input, not the value.
Tried like this:

inputs = $(this).find(':input').not(':button');
$.each(inputs, function(i, val){
inouts = inouts + $(val).prop('outerHTML');
});


Also tried many variations on
$('form#Receiver').append($(this).find('.name') .clone().html())


So, I know what I need to do is find my inputs and clone them...into my wrapper div. How can I store the cloned elements, to put them in a div, like:

$('form#Receiver').append('<div class="appended">' + namediv + inputs + '</div>');


Here is the working result, thanks @Derek Story

addbutt = $("form.prodform button.add");
addbutt.click(function(e){
var inputs = [];
var divs = [];
var theform = $(this).closest('form');
e.preventDefault();
theform.find(':input').not(':button').each(function() {//using :intput cuz it might be selects, etc.
inputs.push($(this).clone());
});
theform.find('div.name').each(function() {
divs.push($(this).clone());
});

var container = $('<div class="appended" />').append(divs, inputs);
$('form#Receiver').append(container);
})


And let me add, in order for clone() to work on selects and textareas, you need this https://github.com/spencertipping/jquery.fix.clone

Answer

To store cloned elements you can push them into an array like:

var inputs = [];
$('input').each(function() {
  inputs.push($(this).clone());
});

To wrap them in a new element, you should be able to do something along the lines of:

// create the wrapper and append the cloned elements
var container = $('<div class="appended" />').append(namediv, inputs); 
// append the wrapper
$('form#Receiver').append(container);

Codepen example