Ashraful Islam Rafi Ashraful Islam Rafi - 2 months ago 9
Ajax Question

Delete and Update dynamically created Table row ID's serially using Jquery

For example I am listing products for sale using ajax, jquery on Table. Where every table row are getting dynamic id's like, row_1, row_2, row_3 etc.

There is an option to remove any of rows, for example second row(row_2) is removed.

So what I want is, after the row gets deleted, the table row id's should get update also, probably a function will do it, for example I don't want it to be row_1, row_3 instead I want it to be row_1, row_2.

Answer

I'd this code already with me somewhere in my project, tweaked little but as per your need.

Jquery part

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){

    $(".remove_tr").click(function(){

        var tr_id = $(this).parent().attr("id");

        var flag = "N"; var row_cnt = 0;

        $("#dummy_table tr").each(function(){

            if( flag == "Y" ){ 

                $(this).attr("id", "row_"+ row_cnt); 
                $(this).children("td:first-child").html("row_"+ row_cnt); 
                $(this).attr("id", "row_"+ row_cnt); 
                row_cnt++; 
            }

            if( flag =="N" && $(this).attr("id") == tr_id){ 

                var rowArr = $(this).attr("id").split("_");
                row_cnt = rowArr[1]; 

                $(this).remove(); flag= "Y";  
            }                                        
        })
    });
});
</script>

HTML part

<table id="dummy_table">
    <?php for($i = 0; $i < 10; $i++){ ?>        
        <tr id="row_<?php echo $i; ?>">
            <td>row_<?php echo $i; ?></td>
            <td class="remove_tr">remove</td>
        </tr> 
    <?php } ?>        
</table>

Let me know if it works for you

Comments