Yan Myo Aung
Yan Myo Aung

Reputation: 398

Jquery click doesn't work after updating with AJAX

I have read some about my problem and still don't get the right answer.I tried .on() method it still doesn't work.I am using Laravel.

@foreach($orders as $order)
   <tr class="item{{$order['menus']['id']}}">
       <td>{{$order['menus']['name'] }}</td>
       <td>{{$order['quantity']}}</td>
       <td>{{$order['quantity'] * $order['menus']['price']}}</td>
       <td><span id="paddingcustom"><span class="glyphicon glyphicon-minus cancelbox " data-menuid="{{$order['menus']['id']}}"></span></span> </td>
       <td></td>
   </tr>
@endforeach

JS

$('.cancelbox').each(function(){
    $(this).on('click',function(){
        $.ajax({
            type : 'POST',
            url  : 'menus/deleteTmp',
            data : {
                '_token' : $('input[name=_token]').val(),
                'id' : $(this).data('menuid'),
            },
            success : function ($data) {
                $('.item' + $data).remove();
            }
        });
    });
});

Everything work I want after loading the page but when I update the elements by using replaceWith() methods and then onclick doesnt work.

I checked my updated html and attributes and all are in the right place.

Upvotes: 1

Views: 93

Answers (1)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72289

You need to use Event Delegation:-

So change::-

$('.cancelbox').each(function(){
  $(this).on('click',function(){

To::-

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

So code need to be:-

$(document).on('click','.cancelbox',function(){
    $.ajax({
        type : 'POST',
        url  : 'menus/deleteTmp',
        data : {
            '_token' : $('input[name=_token]').val(),
            'id' : $(this).data('menuid'),
        },
        success : function ($data) {
            $('.item' + $data).remove();
        }
    });
});

Note:- now apply your replaceWith()code and check

Upvotes: 1

Related Questions