开发者

Delete current row in a <table> with jQuery

I have a table that lists a bunch of customers. The last cell is an ajax delete button.

I want the row containing the deleted customer to be deleted through jQuery.

<table>
<tr><td>Customer info 1</td><td><a href="javascrip开发者_开发知识库t:deleteCustomer(1);">Delete</a></td>
<tr><td>Customer info 2</td><td><a href="javascript:deleteCustomer(2);">Delete</a></td>

function deleteCustomer(customerId)
{
$.post("somepage.php", {cid:customerId}, function(data){
//...delete the row that called the function...
}


Deleting is very relative...

All you really want is the user to not see it anymore. If you select the entire row, you can call toggle() on it, to make it hidden to the user. On the next page load it won't be there anyway (assuming your ajax request deleted it alright), so as long as it is hidden, it is as good as deleted...

Many ways to get back to the row. You can give it a unique ID of customerRow + the id.. so you have rows..

<tr id="customerRow1"> ... </tr>
<tr id="customerRow2"> ... </tr>

Then just call toggle on the element with the id customerRow + customerId

$("#customerRow" + customerId).toggle()

You could also add this as a parameter:

<table>
<tr><td>Customer info 1</td><td><a href="javascript:deleteCustomer(1,this);">Delete</a></td>
<tr><td>Customer info 2</td><td><a href="javascript:deleteCustomer(2,this);">Delete</a></td>

Your function would become:

function deleteCustomer(customerId,element) {
    $.post("somepage.php", {cid:customerId}, function(data){
        $(element).closest("tr").toggle()
    });
}


You could add this as a parameter:

<table>
<tr><td>Customer info 1</td><td><a href="javascript:deleteCustomer(1,this);">Delete</a></td>
<tr><td>Customer info 2</td><td><a href="javascript:deleteCustomer(2,this);">Delete</a></td>

Your function would become:

function deleteCustomer(customerId,element) {
    $.post("somepage.php", {cid:customerId}, function(data){
        $(element).closest("tr").remove();
    });
}

Another approach is to assign an id to each row:

<table>
<tr id='row_1'><td>Customer info 1</td><td><a href="javascript:deleteCustomer(1);">Delete</a></td>
<tr id='row_2'><td>Customer info 2</td><td><a href="javascript:deleteCustomer(2);">Delete</a></td>

Then you delete the row like this:

$("tr[id=row_" + customerId + "]").remove();


I have written an article on the same topic, you can check it out here:

Deleting Table Rows Using JQuery and PHP

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜