Sk Asraf Sk Asraf - 5 months ago 19
Javascript Question

how to take span value which inside <td>(table data),when click button that also inside <td>

i cant understand how to take inside table span id value and also span text when click a button that also in same row

my html code is

<div>
<table id="t1" style="border:1px solid">
<tr><td><span id="city">Chikago</span></td><td><span>USA</span></td><td><button class="show">Show me</button></td></tr>
<tr><td><span id="city">London</span></td><td><span>UK</span></td><td><button class="show">Show me</button></td></tr>
<tr><td><span id="city">Delhi</span></td><td><span>INDIA</span></td><td><button class="show">Show me</button></td></tr>

</table>




using jquery,i am trying to take 2bd row,2nd column value when click the button of 2nd row but i cant understand how to select tanle roes,columns data.

thats why i cant write jquery code.

please give a proper jquery code for this problem.

Answer

You should use closest() and find() to get the spans in the same row. Also, don't reuse ids in your HTML elements.

$(".show").on("click", function() {
  var spans = $(this).closest("tr").find("span");
  var city = spans.eq(0).text();
  var country = spans.eq(1).text();
  console.log(city, country);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="t1" style="border:1px solid">       
  <tr><td><span>Chikago</span></td><td><span>USA</span></td><td><button type="button" class="show">Show me</button></td></tr>
  <tr><td><span>London</span></td><td><span>UK</span></td><td><button type="button" class="show">Show me</button></td></tr>
  <tr><td><span>Delhi</span></td><td><span>INDIA</span></td><td><button type="button" class="show">Show me</button></td></tr>
</table>