Rob
Rob

Reputation:

JQuery, event bubbling on table cells. How to work out which row is clicked on

I have table enclosed by a div that looks similar to this.......

<div id="records">

10 | text1 | Delete
23 | test2 | Delete
24 | text3 | Delete
32 | text4 | Delete

</div>

I'd like to make the "Delete"s clickable which calls an ajax script to remove them from the database.

Each of the 'Delete's has a class of "delete_record"

The table is populated by an ajax script, so to avoid the rebinding issue, I'd like to use event bubbling on "records", so I added a click event on the div "records", and here I check for "delete_record" and currently just have an alert, which seems to work..

$('#records').click(function(event)  {
    if ($(event.target).is('.delete_record'))  {
        alert("clicked on CELL");
    }
});

But what I really want is to access a record_id which the ajax script knows about, and pass this to the ajax script to delete the record. I know how to call this ajax script with the correct values, what I don't know how to do is work out how to get this record _id

10 | text1 | Delete(20389)
23 | test2 | Delete(37474)
24 | text3 | Delete(2636)
32 | text4 | Delete(83731)

So when I click on the second line, the script will call....

$.getJSON("/ajax/delete_record.php",{id: 37474, ajax: 'true'}, function(j){ stuff }

Upvotes: 1

Views: 1312

Answers (1)

xandy
xandy

Reputation: 27411

You said the table is populated from ajax, so, you can actually store your metadata into the table, assuming the following html is generated:

<tr>
    <td>23</td>
    <td>test2</td>
    <td><a>Delete</a></td>
    <td class='id'>37474</td> <!-- Hide the id column in css if needed -->
</tr>

So, just to follow what you did, you if the 'cell' is clicked, then you just go back to parent of it and then look for the td.hasClass('id') and get the text within. Like:

var parentTR = $(event.target).parent('tr'); // Get the parent row
var id = $("td[class='id']", parentTR).html(); // Retrieve the id content

Now you have the id, you can just ajax it to server to delete it.

One more thing to add, I don't really agree on the event binding on the table or the parent div to locate the delete button, it sounds too indirect to me. JQ actually provide a good method to live binding events, try looking at Live Function in JQuery. It actually do a good job for your situation.


Upvotes: 2

Related Questions