3

After adding any row in dataTable, edit or delete button click isn't working. I have done this with ajax. in success function i have destroyed the dataTable. Then load all the data and initiate the dataTable. My codes are following.

HTML Code:

<table class="table table-striped table-bordered bootstrap-datatable datatable">
    <button class="btn btn-success" title="Add Items" id="addCalzone"><i class="halflings-icon white plus"></i> Add Item</button><br/><br/>
    <thead>
        <tr>
            <th>No.</th>
            <th>Name</th>
            <th>Price</th>
            <th>
                <div class="text-center">
                    Action
                </div>
            </th>
        </tr>
    </thead>
    <tbody class="dataTable-tbody">
        <?php foreach($row as $key => $r): ?>
        <tr class="tableRow" data-id="<?= htmlentities(stripcslashes($r['id']), ENT_QUOTES, 'UTF-8'); ?>">
            <td></td>
            <td><?= htmlentities(stripcslashes($r['name']), ENT_QUOTES, 'UTF-8'); ?></td>
            <td> $ <?= htmlentities(stripcslashes($r['price']), ENT_QUOTES, 'UTF-8'); ?></td>
            <td>
                <div class="text-center">
                    <button class="btn btn-info editCalzone" title="Edit"><i class="halflings-icon white edit"></i> Edit</button>
                    <button class="btn btn-danger dltCalzone" title="Delete"><i class="halflings-icon white trash"></i> Delete</button>
                </div>
            </td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>


<div class="modal hide fade" id="addItem">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">×</button>
        <h1>Calzone</h1>
    </div>
    <div class="modal-body">
        <h3>Name</h3>
        <input type="text" id="itemName" value="" required="required" />
        <input type="hidden" id="type" value="add"/>
        <h3>Price</h3>
        <input type="number" min="0" step="0.01" value="" required="required" id="itemPrice" />
    </div>
    <div class="modal-footer">
        <button class="btn btn-primary" id="addClose" data-dismiss="modal">Close</button>
        <button class="btn btn-success" id="addbtn">Save</button>
    </div>
</div>

Javascript Code:

function initDataTable(){
    $('.datatable').dataTable({
        "sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span12'i><'span12 center'p>>",
        "sPaginationType": "bootstrap",
        "oLanguage": {
            "sLengthMenu": "_MENU_ records per page"
        }
    } );
    $('.btn-close').click(function(e){
        e.preventDefault();
        $(this).parent().parent().parent().fadeOut();
    });
    $('.btn-minimize').click(function(e){
        e.preventDefault();
        var $target = $(this).parent().parent().next('.box-content');
        if($target.is(':visible')) $('i',$(this)).removeClass('chevron-up').addClass('chevron-down');
        else                       $('i',$(this)).removeClass('chevron-down').addClass('chevron-up');
        $target.slideToggle();
    });
    $('.btn-setting').click(function(e){
        e.preventDefault();
        $('#myModal').modal('show');
    });
}

$('#addbtn').click(function(){
    var $add = {
        name : $('#itemName').val(),
        cost : $('#itemPrice').val(),
        type : $('#type').val()
    };

    if($add.name == '' || $add.cost == ''){
        alert('Both fields must be filled');
    }else{
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: $calzone.submitURL,
            data: {
                calzoneName: $add.name,
                calzoneCost: $add.cost,
                calzoneAction: $add.type
            },
            cache: false,
            error: function(){
                alert('An Error Occured !!');
            },
            success: function(response){
                alert('Successfully Saved !!');
                $('#itemName').val('');
                $('#itemPrice').val('');
                $('#type').val('');

                $('.datatable').DataTable().destroy();
                $('.dataTable-tbody').html('');
                for(i=0; i<response.length; ++i){
                    var content = '<tr class="tableRow" data-id="' + response[i].id + '">' +
                        '<td>' + (i+1) + '</td>' +
                        '<td>' + response[i].name + '</td>' +
                        '<td>' + response[i].price + '</td>' +
                        '<td>' +
                            '<div class="text-center">' +
                                '<button class="btn btn-info editCalzone" title="Edit"><i class="halflings-icon white edit"></i> Edit</button>&nbsp;' +
                                '<button class="btn btn-danger dltCalzone" title="Delete"><i class="halflings-icon white trash"></i> Delete</button>' +
                            '</div>' +
                        '</td>' +
                        '</tr>';
                    $('.dataTable-tbody').append(content);
                }
                initDataTable();
                $('#addItem').modal('hide');
            }
        });
    }
});

$('.editCalzone').click(function(){
    $('#addItem').modal('show', {
        backdrop: 'static'
    });

    var $edit = {
        name : $(this).closest('tr').find('td').eq(1).text(),
        price : $(this).closest('tr').find('td').eq(2).text().split(' ')[2],
        type : $(this).closest('tr').data('id')
    };

    $('#itemName').val($edit.name);
    $('#itemPrice').val($edit.price);
    $('#type').val($edit.type);
});

$('.dltCalzone').click(function(){
    var $dlt = {
        confirm : confirm("Are you want to delete the selected item ?"),
        key : $(this).closest('tr').data('id')
    };
    if($dlt.confirm){
        $.ajax({
            type: 'POST',
            url: $calzone.submitURL,
            data: {
                deleteKey : $dlt.key
            },
            error: function(){
                alert('An Error Occured');
            },
            success: function(){
                alert('Data has been deleted !!');
                location.reload();
            }
        });
    }else{
        alert('Your data is safe !');
    }
});

The response from the server is perfect. There is no error. But after adding a row or editing a row's information, Edit and Delete button isn't working. But It's working after reload the page. What is the problem in the dataTable initialization, i can't figure out. Please help me to figure out the problem and solve it.

1 Answer 1

18

replace your

$('.editCalzone').click(function(){

$('.dltCalzone').click(function(){

with

 $(document).on('click', '.editCalzone', function(){

$(document).on('click', '.dltCalzone', function(){
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, it's working. Would you please explain your answer ?
when we add some html content dynamiclly, its not bind that is why click event not act. in that case we use $(document). .
it is called "Event Delegation"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.