b22
b22

Reputation: 303

how to get values of columns for a selected row through jQuery

here i am trying to fetch values of a particular column for a selected row via jquery.In Following code i have two rows which do not have any id.I tried following way and getting both rows value for that column appending each other.how to get value for that row only using jquery only.

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript">

function test(){
var id = $(".use-address").closest("tr").find('td:eq(2)').text();
  alert(id);
}
    </script>

</head>
<body>
<table id="choose-address-table" class="ui-widget ui-widget-content">
  <thead>
    <tr class="ui-widget-header ">
      <th>Name/Nr.</th>
      <th>Street</th>
      <th>Town</th>
      <th>Postcode</th>
      <th>Country</th>
      <th>Options</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="nr"><span>50</span>

      </td>
      <td>Some Street 1</td>
      <td>Glas</td>
      <td>G0 0XX</td>
      <td>United Kingdom</td>
      <td>
        <button type="button" class="use-address" onclick="test();">Use</button>
      </td>
    </tr>
    <tr>
      <td class="nr"><span>30</span>
      </td>
      <td>Some Street 2</td>
      <td>Glasgow</td>
      <td>G0 0XX</td>
      <td>United Kingdom</td>
      <td>
          <button type="button" class="use-address" onclick="test();">Use</button>
      </td>
    </tr>
  </tbody>
</table>
</body>
</html>

Upvotes: 6

Views: 55307

Answers (2)

Sharique
Sharique

Reputation: 4219

I would recommend to add class to every column (td), so that it will be easier and more future proof, for example in future you split name to first and last name or you added email after name.. etc.

<td class='country'>United Kingdom</td>

$('.use-address').click(function () {
    var id = $(this).closest("tr").find('td.country').text();
    alert(id);
});

Upvotes: 1

Felix
Felix

Reputation: 38102

You need to use $(this) to target current clicked button instead of $(".use-address"):

function test(){
    var id = $(this).closest("tr").find('td:eq(2)').text();
    alert(id);
}

instead of inline onclick javascript, you can use .click():

$('.use-address').click(function () {
    var id = $(this).closest("tr").find('td:eq(2)').text();
    alert(id);
});

Fiddle Demo

Upvotes: 13

Related Questions