amor amor - 4 months ago 16
HTML Question

Ajax get table value based on row

I can get first and last value from my row but can`t get the second and third value of my row. can anyone help me.

this my code

=> Html

<tr>
<td>one</td>
<td>two</td>
<td>three</td>
<td>four</td>
<td><button class="btnDelete">Delete</button></td>
</tr>


=> javascript

$(".btnDelete").click(function (evt) {
var cell=$(evt.target).closest("tr").children().first();
var cell2=$(evt.target).closest("tr").children().last();
var custID=cell.text();
var custID2=cell2.text();
alert(custID);
alert(custID2);
}


thanks .

Answer

I think it's easier to get this values without jQuery. By using HTMLTableRowElement.cells DOM property. Which is almost like an array, but not an array.

$("#myTable").on('click','.btnDelete',function(){
     // get the current row
     var currentRow = $(this).closest("tr")[0]; 
     var cells = currentRow.cells;

     var firstCell = cells[0].textContent;
     var secondCell = cells[1].textContent;

     //...
     //nthCell = cells[n-1].textContent;
     console.log( firstCell );
     console.log( secondCell );
});

If you still want jQuery, then instead of .first() and .last() methods, you could use .eq() method.

 var rowCells = $(this).closest("tr").children(); 
 var firstCell = rowCells.eq( 0 ).text();
 var secondCell = rowCells.eq( 1 ).text();