Get a comma separated list of first cell values for rows with classname (using Jquery)?
Question
Trying to grab ids from the table below when a row is selected. For example, the jquery should return: "12,14"..My code below returns empty string?
My html:
<table id="display" width="100%">
<thead>
<tr>
<th>ID</th>
<th>first</th>
<th>last</th>
<th>number</th>
</tr>
</thead>
<tbody>
...etc...
<tr class="selected">
<td>12</td>
<td>Bob</td>
<td>Smith</td>
<td>9999</td>
</tr>
<tr>
<td>13</td>
<td>Lee</td>
<td>Smith</td>
<td>8888</td>
</tr>
<tr class="selected">
<td>14</td>
<td>JJ</td>
<td>Wolf</td>
<td>77777</td>
</tr>
... etc..
</table>
My Jquery:
var nameIDs = $('table tr.selected td:first').map(function () {
return this.value;
}).get().join(',');
Solution
The value
is not defined for td, you need to use this.innerText
or this.innerHTML
, Also use first-child
instead of first
var nameIDs = $('table tr.selected td:first-child').map(function () {
return this.innerText;
}).get().join(',');
Edit
The html is also invalid, you missed the closing </td>
in second td
for all rows.
Change
<td>Smith<td>
To
<td>Smith</td>
OTHER TIPS
This code may help you
var elems = $(".selected>td:first-child");
for(var key in elems )
elems[key] = $(elems[key]).html();
var values = elems.join(",");
The result is in the string values
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow