Add/Remove Form Fields Dynamically With jQuery - cloner

File Size: 65.2 KB
Views Total: 4677
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Add/Remove Form Fields Dynamically With jQuery - cloner

A lightweight, flexible form cloner plugin which enables the user to dynamically add/remove/clone form fields and/or form groups in an HTML form.

How to use it:

1. Install the jQuery cloner via NPM or directly download the plugin and then include the JavaScript file jquery.cloner.min.js after jQuery library.

# NPM
$ npm install jquery-cloner --save
<script src="/path/to/cdn/jquery.slim.min.js"></script>
<script src="dist/jquery.cloner.min.js"></script>

2. Initialize the plugin by adding the data-toggle="cloner" attribute to the clonable form block.

<div class="clonable-block" data-toggle="cloner">
  ...
</div>

3. Insert any form fields to be clonable to the form block. That's it. Possible CSS helpers:

  • clonable: CSS selector for the clonable form field
  • clonable-decrement-*: decrements values inside the form field
  • clonable-increment-*: increments values inside the form field
  • clonable-button-add: CSS selector for the Add button
<div class="clonable-block" data-toggle="cloner">
  <div class="clonable" data-ss="1">
    <label for="" class="clonable-increment-html">1 2</label>
    <input id="person_1" class="clonable-decrement-value clonable-increment-placeholder" type="text" name="person[0]" placeholder="person[0][name][1]" value="5 4">
  </div>
  <button class="clonable-button-add" type="button">Add person</button>
</div>

4. You can also initialize the plugin via JavaScript:

$(function(){
  $('#clonable-block').cloner();
});

5. All possible plugin options:

$('#clonable-block').cloner({
  clonableContainer: '.clonable-block',
  clonable: '.clonable',
  addButton: '.clonable-button-add',
  closeButton: '.clonable-button-close',
  focusableElement: ':input:visible:enabled:first',

  clearValueOnClone: true,
  removeNestedClonablesOnClone: true,
  limitCloneNumbers: true,

  debug: false,

  cloneName: 'clonable-clone',
  sourceName: 'clonable-source',

  clonableCloneNumberDecrement: 'clonable-clone-number-decrement',

  incrementName: 'clonable-increment',
  decrementName: 'clonable-decrement',
});

6. Or pass the options via data attribute:

<div class="clonable-block" 
     data-toggle="cloner" 
     data-options='{"clearValueOnClone":false}'>
  ...
</div>

7. Callback functions which will be fired before/after cloning.

$('#clonable-block').cloner({
  beforeToggle: function (clone, index, self) {},
  afterToggle: function (clone, index, self) {}
});

This awesome jQuery plugin is developed by lienoil. For more Advanced Usages, please check the demo page or visit the official website.