Monday, March 20, 2017

Delete button button doesn't work for ajax added rows [duplicate]

This question already has an answer here:

I'm creating dynamic table with AJAX and Laravel. My delete buttons, added in ajax or on 2,3,4... page in pagination just dont't work. I can't even alert them. Buttons on first page, recent loaded by refreshing the page works and deleting whole rows.

JS

    $('button[data-type="addBankHoliday"]').click(function () {
        $.ajax({
            type: 'post',
            url: '/bankholidays/add',
            data: {
                _token: $('input[name=_token]').val(),
                dateRange: $('input[name=dateRangePicker]').val(),
                description: $('input[name=description]').val()
            },
            success: function (bankHoliday) {
                var table = $('#datatable').DataTable();
                $.each(bankHoliday, function (index, value) {
                    table
                        .row
                        .add([
                            moment(value.date.date).format('YYYY-MM-DD'),
                            value.description,
                            $('<td><button data-type="deleteBankHoliday" class="btn btn-danger" data-id="' + value.id + '"><span class="glyphicon glyphicon-trash"></span>Usuń</button></td>').html()
                        ]).draw(false);
                })
            }
        })
    });
    $('button[data-type="deleteBankHoliday"]').click(function () {
        var table = $('#datatable').DataTable();
        var row = table.row($(this).closest('tr'));
        $.ajax({
            type: 'post',
            url: '/bankholidays/delete',
            data: {
                _token: $('input[name=_token]').val(),
                id: $(this).data('id')
            },
            success: function () {
                row
                    .remove()
                    .draw(false);
            }
        })
    });

HTML/Laravel

<table id="datatable" class="table table-striped table-bordered">
    <thead>
    <tr>
        <th width="30%">Dzień</th>
        <th>Opis</th>
        <th width="25%">Usuń</th>
    </tr>
    <tbody>
    @foreach($bankHolidays as $bankHoliday)
        <tr>
            <td></td>
            <td></td>
            <td>
                <button data-type="deleteBankHoliday" class="btn btn-danger" data-id="">
                    <span class="glyphicon glyphicon-trash"></span> Usuń
                </button>
            </td>
        </tr>
    @endforeach
    </tbody>
    </thead>
</table>



via Dawid Olejniczak

Advertisement