When we submit a form, we sometimes encounter the need to repeatedly add multiple same form elements, such as adding multiple different models of products to the order information, adding new field information to the form data, etc. At this time, we can place a "Add an item" or "Copy" button directly in the form, and copy the form elements by clicking the button.
View demo Download source code
HTML
In this article, we introduce a simple jQuery-based element copy plug-in through an example. The element copy function can be easily realized by calling this plug-in.
First load the jQuery library file and element duplication plug-in duplicateElement.min.js.
<script src="jquery.js"></script> <script src="duplicateElement.min.js"></script>
We assume that we need to copy user information elements. The form html structure is as follows:
<form id="myform" name="myform" action="post.php" method="post"> <fieldset id="additional"> <label for="name">客户姓名:</label> <input id="name" name="name[]" type="text" class="input" > <label for="flag">客户级别:</label> <select id="flag" name="flag[]"> <option disabled="" selected="">请选择</option> <option value="1">VIP</option> <option value="2">普通</option> </select> <a href="javascript:void(0);" class="btn remove">移除</a> <a href="javascript:void(0);" class="btn create">复制</a> </fieldset> <br/> <div class="sub_btn"> <input type="submit" class="button" value="提交"> </div> </form>
jQuery
When we click the "Copy" button, the content in #additional will be copied, which is equivalent to adding a new line. Initially, only the "Copy" button will be displayed. After copying, the original line will display "Remove" button, click "Remove" to remove the corresponding row.
$(function () { $('#additional').duplicateElement({ "class_remove": ".remove", "class_create": ".create", onCreate: function (el) { el.find("select").prop('defaultSelected'); el.find(".input").val(''); } }); });
We can also use the onCreate() callback function to define the attributes of the newly added form elements after successful copying, such as form element values or styles, etc.
The above content is a jQuery copy form element with source code sharing effect demonstration shared with you. I hope it will be helpful to everyone.