When we submit a form, we sometimes encounter the need to repeatedly add multiple identical form elements, such as order information need to add a number of different models of products, tables
New field information in single data. This time we can place a "new item" or "Copy" button directly in the form, and then copy the form element by clicking the button.
In this paper, we introduce a simple jquery based element replication plug-in, which can easily implement the element replication function by invoking the plug-in.
first load the jquery library file and the element replication plug-in duplicateElement.min.js.
<script src= "Jquery.js" ></script>
<script src= "DuplicateElement.min.js" ></script>
We assume that the user information element needs to be replicated, and the form HTML structure is as follows:
<form id= "MyForm" name= "MyForm" action= "post.php" method= "POST" >
<fieldset id= "Additional" >
<label for= "name" > Customer name:</label>
<input id= "name" Name= "name[]" type= "text" class= "input" >
<label for= "Flag" > Customer level:</label>
<select id= "Flag" name= "flag[]" >
<option disabled= "" selected= "> Please select </option>
<option value= "1" >VIP</option>
<option value= "2" > General </option>
</select>
<a href= "javascript:void (0);" class= "btn Remove" > Removal </a>
<a href= "javascript:void (0);" class= "btn Create" > Replication </a>
</fieldset>
<br/>
<div class= "SUB_BTN" >
<input type= "Submit" class= "button" value= "submitted" >
</div>
</form>
Jquery
We click on the "Copy" button, the contents of the #additional to copy, the equivalent of a new line, the initial time only show "Copy" button, after the copy, the original piece will show the "Remove" button, click "Remove" can be the corresponding row removed.
$ (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 properties of new form elements, such as form element values or styles, after replication succeeds.