Created
May 28, 2020 19:34
-
-
Save esson/c02b5f9a3eadc5152639d92f53a4cb40 to your computer and use it in GitHub Desktop.
Add and remove inputs for form arrays.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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