Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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>
like image 200
b22 Avatar asked Mar 25 '14 13:03

b22


2 Answers

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);
});
like image 34
Sharique Avatar answered Nov 20 '22 21:11

Sharique


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

like image 177
Felix Avatar answered Nov 20 '22 21:11

Felix