sam
sam

Reputation: 459

Get first cell value of each row in table

Please help me to get first cell value of each row in table by click delete button, the below codes display cell values for all the cells. The table is generated by Ajax success function. So the table does not exist on page on-load.

<script type="text/javascript">
$(document).ready(function() {
     $("#mytable td").click(function() {
     alert($(this).html());
     });
 });

</script>


 //html table , this is sample table , 

 <table border="1" id="mytable">
  <tr>
    <th>Customer Id</th>
    <th>Action</th>
  </tr>
  <tr>
    <td>0001</td>
    <td><button>Del</button></td>
  </tr>
  <tr>
    <td>0002</td>
    <td><button>Del</button></td>
  </tr>
  <tr>
    <td>0003</td>
    <td><button>Del</button></td>
  </tr>
</table>

Upvotes: 2

Views: 8245

Answers (4)

amichai
amichai

Reputation: 728

to get an array of all the values of the i'th column you can use

var i=0;
$('tr > td:nth-child(i)').map(function () { return $(this).text(); }).get();

Upvotes: 0

Sergio
Sergio

Reputation: 28837

This does what you are looking for:

$("#mytable td").click(function () {
  var selectValue = $(this).siblings("td").html();
  alert(selectValue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table border="1" id="mytable">
  <tr>
    <th>Customer Id</th>
    <th>Action</th>
  </tr>
  <tr>
    <td>0001</td>
    <td><button>Del</button></td>
  </tr>
  <tr>
    <td>0002</td>
    <td><button>Del</button></td>
  </tr>
  <tr>
    <td>0003</td>
    <td><button>Del</button></td>
  </tr>
</table>

JSFiddle demo of the code above.

Upvotes: 3

Sam
Sam

Reputation: 42377

I think this should get the first table cell of each row.

$('tr > td:first-child')

Upvotes: 4

papaiatis
papaiatis

Reputation: 4291

This is how you can get the first cell's text by clicking on a button in the same table row:

$(document).on("click", "table td button", function(){
    alert($(this).parents("tr").find("td:first").text());
});

Since it's using jQuery.on() it works with AJAX generated tables as well.

jsFiddle DEMO: http://jsfiddle.net/fZ639/

Upvotes: 1

Related Questions