Get elements of HTML TR when a button in the row is clicked

2.4k Views Asked by At

I have the following Dynamic HTML row.

<tr role="row" class="odd">
     <td contenteditable="false" class="sorting_1"> </td>
     <td contenteditable="false"> <span class="name">Alex Nilson </span></td>
     <td contenteditable="false"><span class="price"> 1234 </span></td>
     <td contenteditable="false"> <span class="qty" >1234 </span></td>
     <td><button class="pr_edit" href="javascript:;"> Edit </button></td>
     <td><button class="pr_elete" href="javascript:;"> Delete </button></td>
</tr>

When the edit button is clicked, I need to get the values of the cell elements of that particular row into jQuery, as JS variables, that I can AJAX POST to another PHP page to insert into database. I tried to do it like the following, but it didn't pan out.

$(document).ready(function () {
     $('.pr_edit').click(function () {
         var currentTD = $(this).parents('tr').find('td');            
         $.each(currentTD, function () {
             var iname = $(this).find("span.name").html();
             var iprice = $(this).find("span.price").val();
             var iqty=$(this).find("span.qty").val();
         });

It doesn't catch the variables as I intended.How do I achieve this? I need to get these SPAN data to three variables.

2

There are 2 best solutions below

5
On BEST ANSWER

You need event delegation for dynamically generated elements and use text() instead of val() to get the content of span. Also use closest('tr') to get parent tr, you don't need to use each.

$(document).ready(function () {
     $('body').on('click', '.pr_edit', function () {
         var currentTR = $(this).closest('tr');
         var iname = currentTR.find("span.name").text();
         var iprice = currentTR.find("span.price").text();
         var iqty = currentTR.find("span.qty").text();
     });
 });      
0
On

If you want to work with dynamic data and jQuery, you need to bind your click-event dynamically to. instead :

$('.pr_edit').click(function () {
    //magic
}

do

$('.pr_edit').on('click', function () {
    //magic
}

but if even your whole table is being loaded dynamically, you have to have an element thats "allways" there as a reference. like:

$('html, body').on('click', '.pr_edit', function () {
  //magic
}

Check this out for refference: http://api.jquery.com/on/