Salar Muhammad
Salar Muhammad

Reputation: 334

Get the cell value of a particular column from html table in Jquery

I want to get the cell value of a particular column from html table using JQuery. I have table that contains data of transaction, fetched from database. Along with this, contains a column having button that inserts transaction. What I want is that, when I click on that button, I should be getting the cell value from that particular row.

enter image description here

I have tried following line of code, but that didn't work.

$(".btn").click(function () {
    var texto = $('table tr:nth-child(1) td:nth-child(2)').text()
    alert(texto)
});

Upvotes: 1

Views: 1675

Answers (2)

Nawaz Ghori
Nawaz Ghori

Reputation: 591

here you need to point out the row in which you have clicked the button and in that you need to get cell value. Here is my code:

$(".btn").click(function () {
    var $row = $(this).parents('tr');
    var texto = $row.find('td:nth-child(5)').text();
    alert(texto);
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table width="100%" border="1">
  <tr>
    <td>date</td>
    <td>name</td>
    <td>department</td>
    <td>departmentcode</td>
    <td>id</td>
    <td>cash</td>
    <td>and<t/d>
    <td><button class="btn">ADD TRANSACTION</button></td>
  </tr>
  <tr>
    <td>date2</td>
    <td>name2</td>
    <td>department2</td>
    <td>departmentcode2</td>
    <td>id2</td>
    <td>cash2</td>
    <td>and2<t/d>
    <td><button class="btn">ADD TRANSACTION</button></td>
  </tr>    
  
  
</table>

Upvotes: 2

Liam
Liam

Reputation: 6743

https://jsfiddle.net/Liamm12/vca4qdrn/

There's no <td> in your first <tr>

$('.btn').on('click', function(){
	 var texto = $('table tr:nth-child(2) td:nth-child(3)').text();
  	alert(texto)
});
table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
}

tr:nth-child(even) {
    background-color: #dddddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<table>
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
    <th>Button</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
     <td><button class="btn">
     get country Value
     </button></td>
  </tr>
  <tr>

</table>

Upvotes: 0

Related Questions