I make this script in jQuery to add and remove fields, first I separate the functions in object literal way, and I can add fields by cloning the div. But I can't bind the remove button to cloned element.
<!--html with text field -->
<div class="row" id="descripcion_pregrado">
<div class="col-xs-8 col-sm-8 col-lg-8">
<div class="form-group">
{{ Form::label('descripción', 'Descripción: *')}}
{!! Form::text('descripcion_pregrado[]',null,
array(
'class'=>'form-control'
)) !!}
</div>
</div>
<div class="col-xs-3 col-sm-3 col-lg-3">
<div class="form-group">
{{ Form::label('dedicacion', 'Dedicación Horas Semanales: *') }}
{!! Form::number('dedicacion_pregrado[]',0,
array(
'class'=>'form-control',
'min'=>0,
'step'=>'.01'
)) !!}
</div>
</div>
<div class="col-xs-1 col-sm-1 col-lg-1" style="padding-top:0px">
<div class="form-group">
<a href="javascript:void(0);" class="add_button plus-minus" title="Add field"> <span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span></a>
</div>
</div>
</div>
Here is the jQuery it works with add field but it doesn't with remove field
(function () {
var campos = {
config: {
start: 0,
max: 9,
},
init: function (config) {
$.extend(campos.config.config);
this.cacheDom();
this.bind();
},
cacheDom: function () {
this.$el = $("#descripcion_pregrado");
this.$button = this.$el.find("a");
this.$remove = this.$el.find(".remove_button");
},
bind: function () {
this.$button.on('click', this.addField.bind(this));
this.$remove.on('click', this.removeField.bind(this));
},
addField: function () {
if (campos.config.start < campos.config.max) {
var cloned = this.$el.clone();
this.$el.after(cloned);
cloned.find('span').attr('class', 'glyphicon glyphicon-minus-sign');
cloned.find('a').attr('class', 'remove_button plus-minus');
this.config.start++;
} else {
alert('max ' + campos.config.max + ' inputs');
}
},
removeField: function () {
console.log($(e.target));
var $remove = $(e.target).closest(this.$el).remove();
this.cacheDom();
}
}
campos.init();
})();