I am trying to console.log the value of a row in a table. I am able to console.log the row index on click, but outputting the actual row value is proving a bit more challenging. I'm pretty new at JavaScript, so I suspect (and hope) it's something simple and a lightbulb opportunity as well.
HTML
<form id="location-form">
<textarea name="excel_data" id="data-paste" class="form-control
form-control-md" style="height:150px;"></textarea><br>
<button type="submit" class="btn btn-primary btn-block"
style="margin: 0 auto; width: 50%;"
onclick="javascript:generateTable(); return false;">Submit
</button>
</form>
<h2 style="text-align: center;">Table will appear below: </h2>
<div class="location-table" style="margin:25px auto;">
<table id="excel_table" class="table loc-table table-sm table-hover table-bordered" style="width:100%;"></table>
</div>
JavaScript
// Get data inserted into the textarea and put in table below it //
function generateTable() {
var data = $('textarea[name=excel_data]').val();
console.log(data);
var rows = data.split("\n");
var table = $('<table id="new_table" />');
for (var y in rows) {
var cells = rows[y].split("\t");
var row = $('<tr />');
for (var x in cells) {
row.append('<td>' + cells[x] + '</td>');
console.log(cells[x]);
}
// only append rows with text - do not append blank rows
if (cells[x].length > 0) {
table.append(row);
}
}
// Insert into DOM
$('#excel_table').html(table);
// Action when click on a row in the table
var locTable = document.getElementById('new_table'), rIndex;
for(var i = 0; i < locTable.rows.length; i++)
{
locTable.rows[i].onclick = function()
{
rIndex = this.rowIndex;
console.log("the value of the rIndex variable is " + rIndex);
var loc_string = this.rows[rIndex].innerHTML;
console.log(JSON.stringify(loc_string));
}
}
}
It's something in the last block of code in the click event. I probably included too much code, but for context, I included the code that creates the table from values in a textarea.
It's giving me "110 Uncaught TypeError: Cannot read property '0' of undefined at HTMLTableRowElement.locTable.rows..onclick"