b22
b22

Reputation: 303

how to get values of columns for a selected row through jQuery on click of element calling method to retrieve value

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.I want to call test function on click of that element, dont want to use http://jsfiddle.net/SSS83/

<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: 1

Views: 11085

Answers (2)

xiidea
xiidea

Reputation: 3394

Not sure why you don't want to use jQuery Click event!!

Any way, if you want to stick with your test function, you need to tell the function from where it got called.

so change the

<button type="button" class="use-address" onclick="test();">Use</button>

to

<button type="button" class="use-address" onclick="test(this);">Use</button>

And update your test function as

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

Enjoy!!


If you change your mind you can use the following code

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

Upvotes: 7

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114377

Based on a click of a TD:

$('td').on('click',function() {
      //get the column of the TD
      var myCol = $(this).index();

      //loop through the rows of this table, get the TD in the same column
      $(this).parent('table').find('tr').each(function() {
         var colValue = $(this).find('td').eq(myIndex).html()
      }
})

"colValue" in the loop will grab the contents of the TD at that position.

Upvotes: 0

Related Questions