Reputation: 73
I am trying to grab the id's from all td's that I have. Below is the my html table
<table class="dummyclass">
<tbody>
<tr>
<td>ID</td>
<td>Status</td>
<td>Description</td>
<td><input type='checkbox' id='select_all'></td>
</tr>
<tr>
<td>100</td>
<td>TestStatus</td>
<td>TestDescription</td>
</tr>
<tr>
<td>101</td>
<td>TestStatus1</td>
<td>TestDescription1</td>
</tr>
</tbody>
</table>
and in the jquery function
$('#select_all').live('click', function () {
if(this.checked) {
// i need to fetch all id's from all td's
// 100,101
}
});
Upvotes: 0
Views: 696
Reputation: 1826
I think this is what you want:
$('#select_all').on('click', function(evt) {
var ids = [];
var $cells = $('tbody td:first-child');
$cells.each(function() {
ids.push(parseInt($(this).text(), 10));
});
console.log(ids);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type='button' id='select_all'>Select All</button>
<table>
<thead>
<th>ID</th>
<th>Status</th>
<th>Description</th>
</thead>
<tbody>
<tr>
<td>100</td>
<td>TestStatus</td>
<td>TestDescription</td>
</tr>
<tr>
<td>101</td>
<td>TestStatus1</td>
<td>TestDescription1</td>
</tr>
</tbody>
</table>
Note that I converted your checkbox to a <button>
element and moved it outside of the table, since it’s a UI element and not tabular data. I also updated the table to use thead
and th
for better accessibility and to make it easier to exclude the header cells.
Hope that helps!
P.S. If you need live()
functionality, you can use event delegation and do something like $('body').on('click', '#select_all', function(evt) { … });
Upvotes: 0
Reputation: 4052
<thead></thead>
$('tbody td:first-child').map(function(index,ele){
return $(ele).text()
}).toArray()
Upvotes: 1
Reputation:
Traverse up to the ancestor tr
by using .closest()
, then use .nextAll()
and .find()
to get the td
elements that have the IDs, then .map()
with toArray()
to create an array of the IDs.
$('#select_all').live('click', function() {
if (this.checked) {
var ids = $(this).closest("tr")
.nextAll("tr")
.find("td:first-child")
.map(function(i, el) { return el.textContent })
.toArray();
console.log(ids);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<table class="dummyclass">
<tbody>
<tr>
<td>ID</td>
<td>Status</td>
<td>Description</td>
<td>CLICK ME: <input type='checkbox' id='select_all'></td>
</tr>
<tr>
<td>100</td>
<td>TestStatus</td>
<td>TestDescription</td>
</tr>
<tr>
<td>101</td>
<td>TestStatus1</td>
<td>TestDescription1</td>
</tr>
</tbody>
</table>
Also, putting your first row in a thead
and the rest in a tbody
would be a good idea.
Upvotes: 0
Reputation: 39
You can easily grab it by checking first column of the table.
Check this:
$('tr').each(function() {
console.log($(this).find('td:first').text());
})
Upvotes: 0