Joe Slater Joe Slater - 5 months ago 10
HTML Question

How to get the value within a table cell?

So I have the following code:

Please look at the JSFiddle: https://jsfiddle.net/gL2emr8h/3/

I want to get the value of the ID of the selected row. I dont know which function to use to get the value of the first cell from the selected row. At the moment, it is coming out to be undefined.

<table class="table table-striped" style="min-width: 100%;">
<tr>
<th>Id</th>
<th>Name</th>
<th>Type</th>
</tr>
<tr>
<td>1</td>
<td>Name1</td>
<td>Type1</td>
</tr>
<tr>
<td>2</td>
<td>Name2</td>
<td>Type2</td>
</tr>
</table>


CSS:

tr {
background: #00eeff;
}

.active {
background: #ff5500;
}


JavaScript:

var selectedHazardId;

$(function() {

/* Get all rows from your 'table' but not the first one
* that includes headers. */
var rows = $('tr').not(':first');

/* Create 'click' event handler for rows */
rows.on('click', function(e) {

/* Get current row */
var row = $(this);
rows.removeClass('active');
row.addClass('active');

selectedHazardId = row.children('td')[0].html();
console.log(selectedHazardId);
});
});

Answer

Pulling an item out of a JQuery array by index (e.g. $("*")[0]) will give you a DOM object that does not have the $.html() function. To use this method you would need to access the textContent property:

selectedHazardId = row.children('td')[0].innerHTML;

To pull an item out of a jQuery array while keeping it a JQuery object you need to use $.eq().

selectedHazardId = row.children('td').eq(0).html();

Alternatively, :eq() can be used as a selector:

selectedHazardId = row.children('td:eq(0)').html();