Kemat Rochi
Kemat Rochi

Reputation: 952

How to get the contents of a cell in a table using jQuery?

I have a Bootstrap table like this,

<table class="table table-striped table-bordered">
    <tr><th>First Name</th><th>Last Name</th><th>Age</th><th>Delete</th></tr>
    <tr><td>Mickey</td><td>Mouse</td><td>5</td><td><button type="submit" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-search"></span></button></td>
    <tr><td>Tom</td><td>Cat</td><td>6</td><td><button type="submit" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-search"></span></button></td>
    <tr><td>Pooh</td><td>Bear</td><td>4</td><td><button type="submit" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-search"></span></button></td>
    <tr><td>Donaled</td><td>Duck</td><td>7</td><td><button type="submit" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-search"></span></button></td>
    <tr><td>Jerry</td><td>Mouse</td><td>8</td><td><button type="submit" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-search"></span></button></td>
</table

When a user clicks on a search button, I want to output the firstname, which is the first cell of that row to another <div>. How can we achieve this using jQuery?

Here's a link to what I've done so far - http://jsbin.com/xenapucisi/edit?html,output

Upvotes: 0

Views: 40

Answers (1)

Xzandro
Xzandro

Reputation: 977

This should do the trick.

$('button').click(function() {
  var tr = $(this).parents('tr');
  var name = $('td:first', tr).text();
  $('#output').html(name);
});

http://jsbin.com/gutivujewu/1/edit?html,js,output

Upvotes: 2

Related Questions