Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Clone <div> with form elements, including their values

I have a Django formset, which has lots of form elements. I have a working method to create a new empty form, but I also need a solution to copy a form. Technically, all forms are in a div, like this:

<form>
...
    <div class="subform">
         ...
    </div>
...
</form>

The problem is, that in latest jQuery versions, html and replaceWith methods don't handle input values, so they create empty form elements instead - which is not the behavior I need. Of course I could implement an algorithm which iterates over all the elements, copies them and sets their values, but I'd like to avoid it if possible.

I want to replace an existing form with the copied values.

like image 568
kdani Avatar asked May 05 '26 12:05

kdani


1 Answers

Yes can use clone() and replaceAll() instead of html()/replaceWith(). clone() will preserve the value properties of your <input> elements, and can even preserve event handlers and custom data.

You can write something like:

var theForm = $("selector-matching-your-form");
theForm.clone(true).replaceAll(theForm);
like image 100
Frédéric Hamidi Avatar answered May 08 '26 05:05

Frédéric Hamidi



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!