Question

I want to detach a row when user clicked to a specific button inside row and append it to another table again and again.

My below script detaches and appends the other row once. However it continues toggling classes on following clicks, it doesn't make detach and append. It also cannot update the db.

What is wrong with this snippet?

$('.orderHideBtn').on('click',function(){
    var $oid = $(this).attr('id').split('-');
    $data = 'a=hideOrder&oid='+$oid[1];
    $.ajax({
        data: $data,
        success: function(msg){
            $('#hbtn-'+$oid[1]).toggleClass("orderHideBtn orderShowBtn").toggleClass('icon-eye-close icon-eye-open').closest('tr').detach().appendTo('#ordersTBody2');
            console.log('#hbtn-'+$oid[1]);
        }
    });
});
$('.orderShowBtn').on('click',function(){
    var $oid = $(this).attr('id').split('-');
    $data = 'a=showOrder&oid='+$oid[1];
    $.ajax({
        data: $data,
        success: function(msg){
            $('#hbtn-'+$oid[1]).toggleClass("orderShowBtn orderHideBtn").toggleClass('icon-eye-open icon-eye-close').closest('tr').detach().appendTo('#ordersTBody1');
            console.log('#hbtn-'+$oid[1]);
        }
    });
});

These are HTML buttons:

<span id="hbtn-{$o.orderID}" class="orderHideBtn icon-eye-close"></span>

and

<span id="hbtn-{$o.orderID}" class="orderShowBtn icon-eye-open"></span>
Was it helpful?

Solution

As you are switching class and selector relative to hanlder is not re-evaluated, you should delegate event, e.g:

$(document.body).on('click','.orderHideBtn',function(){
    var $oid = this.id.split('-');
    $data = 'a=hideOrder&oid='+$oid[1];
    $.ajax({
        data: $data,
        success: function(msg){
            $('#hbtn-'+$oid[1]).toggleClass("orderHideBtn orderShowBtn").toggleClass('icon-eye-close icon-eye-open').closest('tr').appendTo('#ordersTBody2');
            console.log('#hbtn-'+$oid[1]);
        }
    });
});

I removed detach() method because, as i'm aware of, it is useless here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top