jQuery Code:
- jQuery(document).ready(function () {
- /*
- * Give an attribute to anchor tag 'js-add' and the value of that attribute
- * to be his parent selector which is to be copied and to be added after it.
- * For example if you provide <a js-add=".js-field_row">text</a>
- * On click of this element will copy its parent element having class js-field_row
- * and will after it.
- * */
- jQuery(document).on('click', 'a[js-add]', function () {
- var element_to_clone_selector = jQuery(this).attr('js-add');
- var element_to_clone = jQuery(this).parents(element_to_clone_selector);
- var duplicate_element = element_to_clone.clone();
- element_to_clone.after(duplicate_element);
- });
-
- /*
- * Give an attribute to anchor tag 'js-remove' and the value of that attribute
- * to be his parent selector which is to be deleted.
- * For example if you provide <a js-remove=".js-field_row">text</a>
- * On click of this element will remove its parent element having class js-field_row
- * */
- jQuery(document).on('click', 'a[js-remove]', function () {
- var removable_element_selector = jQuery(this).attr('js-remove');
- var removable_element = jQuery(this).parents(removable_element_selector);
- //count all siblings, if its more than 1, delete the selected element.
- var total_row = removable_element.siblings(removable_element_selector).length;
- if (total_row > 0) {
- removable_element.remove();
- } else {
- alert('There should be at least one row');
- }
- });
-
- });
Add two buttons inside the row to add and remove the row like:
<a class="btn btn-success" js-add=".js-field_row">+</a> <a class="btn btn-danger" js-remove=".js-field_row">-</a>
Inside js-add
and js-remove
attribute of the buttons add the selector of the row. For example if you want to add/ remove row on the basis of class add .class_name
.
HTML Code example:
- <div class="row table-striped form-group js-field_row">
- <div class="col-sm-3">
- <div class="form-group field-templatemeta-field_name required">
- <input type="text" id="templatemeta-field_name" class="form-control" name="TemplateMeta[field_name][]" maxlength="25">
-
- <div class="col-sm-3">
- </div>
- <div class="col-sm-1">
- </div>
- <div class="col-sm-3 js-field_value_col">
- <div class="form-group field-templatemeta-field_value">
- <input type="hidden" id="templatemeta-field_value" class="js-field_value" name="TemplateMeta[field_value][]">
-
- </div>
- </div>
- <div class="col-sm-2 pull-right">
- </div>
- </div>