Skip to content

Instantly share code, notes, and snippets.

@esson
Created May 28, 2020 19:34
Show Gist options
  • Save esson/c02b5f9a3eadc5152639d92f53a4cb40 to your computer and use it in GitHub Desktop.
Save esson/c02b5f9a3eadc5152639d92f53a4cb40 to your computer and use it in GitHub Desktop.
Add and remove inputs for form arrays.
(function ($) {
$.fn.dynamicForm = function (options) {
var config = $.extend({}, $.fn.dynamicForm.defaults, options),
$this = $(this),
$inputs = $this.find(config.container),
$add = $this.find(config.addButton),
$remove = $this.find(config.removeButton),
counter = $inputs.children().length;
$add.on('click', function (e) {
$inputs.append(config.templateFactory(counter++, config.inputName));
$remove.prop('disabled', counter < 1);
});
$remove.on('click', function (e) {
if (counter > -1) {
$inputs.children().last().remove();
counter--;
}
$remove.prop('disabled', counter < 1);
});
$remove.prop('disabled', counter < 1);
return this;
};
$.fn.dynamicForm.defaults = {
container: '.controls',
addButton: '.btn-add',
removeButton: '.btn-remove',
inputName: '',
templateFactory: function (i, inputName) { return '<input type="text" class="form-control mb-1" name="' + inputName + '[' + i + ']" />'; }
};
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment