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.
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();
});
});