The50 The50 - 6 months ago 21
HTML Question

JS Dynamically added fields - delete button not working

The problem is that then I add some input fields dynamically, the on click action which should delete the added row is not working. I know that click action has to use .on but it didn't helped. Any ideas?

Here is the .js file:

$(document).ready(function() {

$('.eventsRowsWrapper').each(function() {
var $wrapper = $('.eventsRows', this);

$(".addEventButton", $(this)).on('click', function() {
//console.log(jsFrontend.data.get('Planning.test'));
//$('.multi-event:first-child').clone(true).appendTo($wrapper).find('input').val('').attr('id', '');
$($wrapper).append('<div class="form-group multi-event controls form-inline"> <input name="date[]" maxlength="255" type="text" placeholder="Data" class="datepickerClass form-control sortable ui-sortable" size="20"> <button type="button" style="float: none" class="close deleteEventButton">&times;</button></div>');
$(".datepickerClass").datepicker();
$('.sortable').sortable();
});

$('.multi-event').on('click', '.deleteEventButton', function() {
if ($('.multi-event', $wrapper).length > 1){
$(this).parent('.multi-event').remove();
}
});
});

});


And .html:

<div class="eventsRowsWrapper">
<div class="eventsRows sortable">
<div class="form-group multi-event controls form-inline">
<input name="date[]" maxlength="255" type="text" placeholder="Data" class="datepickerClass form-control sortable ui-sortable" size="20">
<button type="button" style="float: none" class="close deleteEventButton">&times;</button>
</div>
</div>

<button class="btn btn-warning btn-sharp addEventButton" type="button" name="addEvent">
<span class="glyphicon glyphicon-plus-sign"></span>Add event
</button>
</div>


Here is the Fiddle.

Answer

instead of:

$('.multi-event').on('click', '.deleteEventButton', function() {

write:

$(document).on('click', '.multi-event .deleteEventButton', function() {

You are trying to attach an handler on something that does not exist in the dom yet.