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>
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);
});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With