Push Object to array, with selector on properties - javascript

I have a simple piece of code that in my mind should work
HTML
<table cellpadding="0" cellspacing="0" border="0">
<tbody><tr>
<th scope="row">Quantity</th>
<th id="js-QuantityID-1" scope="col">1</th>
<th id="js-QuantityID-2" scope="col">2</th>
<th id="js-QuantityID-3" scope="col">3</th>
<th id="js-QuantityID-4" scope="col">4</th>
<th id="js-QuantityID-5" scope="col">5</th>
<th id="js-QuantityID-6" scope="col">10</th>
<th id="js-QuantityID-7" scope="col">15</th>
<th id="js-QuantityID-8" scope="col">20</th>
<th id="js-QuantityID-9" scope="col">30</th>
<th id="js-QuantityID-10" scope="col">40</th>
<th id="js-QuantityID-11" scope="col">100</th>
</tr>
<tr>
<th scope="row">Price (inc. VAT)</th>
<td id="js-PriceID-1">£45.60</td>
<td id="js-PriceID-2">£76.80</td>
<td id="js-PriceID-3">£97.20</td>
<td id="js-PriceID-4">£128.40</td>
<td id="js-PriceID-5">£172.80</td>
<td id="js-PriceID-6">£307.20</td>
<td id="js-PriceID-7">£402.00</td>
<td id="js-PriceID-8">£432.00</td>
<td id="js-PriceID-9">£630.00</td>
<td id="js-PriceID-10">£840.00</td>
<td id="js-PriceID-11">£2100.00</td>
</tr>
</tbody>
</table>
Javascript
function getTableContents() {
var productArray = [];
for (var x = 0; x <= 12; x++) {
productArray.push({ Price: $('#js-PriceID-' + x).text(), Qty: $('#js-QuantityID-' + x).text() });
}
console.log("Array: " + productArray);
}
But at the end of the execution of this code, I end up with an array with the two properties 'undefined'. If I manually enter the selector ID it works fine, it seems to be with the for loop and getting the values at runtime.
Why is this and is there a workaround?

First item in the loop is 0, and last item is 12. That's why.
Try your loop as follows:
for (var x=1; x<=11; x++)

The loop runs from 0 until 12 so it will look up js-PriceID-0 and js-PriceID-12, which both don't exist. Same goes for js-QuantityID-0and js-QuantityID-12.
Use this instead:
for (var x = 1; x < 12; x++) {
productArray.push({ Price: $('#js-PriceID-' + x).text(), Qty: $('#js-QuantityID-' + x).text() });
}
To save some time you could also do something like this:
function getTableContents() {
var productArray = [];
// loop through all elements with an id that starts with "js-QuantityID-"
$("th[id^='js-QuantityID-']").each(function () {
var n = $(this).attr("id").replace('js-QuantityID-',''); // get the number from the id
productArray.push({
Price: $('#js-PriceID-' + n).text(),
Qty: $(this).text()
});
});
console.log("Array: ", productArray);
}

Related

jQuery - Combine <TR>(s) values that are in same Section # with same Group # / remove duplicates

I have updated the code, which is currently working up to the Place for each Group #. The existing code determines a matching Section # with Group #, and combines the TR values, adding the Average(s) and dividing by the number of TR(s), and removing any duplicate(s).
I am attempting to determine a Place for each Group # within a Section #. (*example - Section 1: Group #1 - 1st / Group #2 - 3rd / Group #3 - 2nd)
$(function() {
alert('View Table Before Grouping');
sort_array();
combine_rows();
compute_average();
});
//function sort_array
function sort_array() {
var $table = $('table');
var header = $('table tr:first-child').html();
var l = [];
$table.find('tr').each( function() {
//get values from td(s) from each row
var section = $(this).find('.class_section_number').text();
var group_number = $(this).find('.group_number').text();
var average = $(this).find('td:eq(2)').text();
var place = $(this).find('td:eq(3)').text();
//add to array
l.push([section, group_number, average, place]);
//remove saved row
$(this).remove();
});
l = l.slice(1);
//sort the array by section #, then group #
l.sortBy(0, true, 1, true, 2, false);
$table.prepend(header);
//rebuild table after sort
$.each(l, function(key, value) {
$('table').append('<tr><td class="class_section_number">' + value[0] + '</td><td class="group_number">' + value[1] + '</td><td class="grade">' + value[2] + '</td><td>' + value[3] + '</td></tr>');
});
}
//function combine_rows
function combine_rows() {
$('table tr').each( function() {
//get current row data
var section = $(this).find('.class_section_number').text();
var group = $(this).find('.group_number').text();
var average = $(this).find('td:eq(2)').text();
//get next row data
var next_section = $(this).next('tr').find('.class_section_number').text();
var next_group = $(this).next('tr').find('.group_number').text();
var next_average = $(this).next('tr').find('td:eq(2)').text();
//check for section # / group # row match
if ((section === next_section) && (group === next_group)) {
//check for empty average
if (average === 'No Data') {
average = 0 + ',' + next_average;
}
else {
average = average + ',' + next_average;
}
//set combined average
$(this).next('tr').find('td:eq(2)').text(average);
//remove matching row
$(this).remove();
}
});
}
//function compute_average
function compute_average() {
$('table tr').each( function() {
//get average from row
var average = $(this).find('td:eq(2)').text();
//split average into array (*if comma separated values)
average_array = average.split(',');
var total = 0;
//total average values from array / divide by count and set
for (var i = 0; i < average_array.length; i++) {
total += (+average_array[i]);
$(this).find('td:eq(2)').text((total / average_array.length).toFixed(2));
}
});
}
//array sort function
Array.prototype.sortBy = function (propertyName, sortDirection) {
var sortArguments = arguments;
this.sort(function (objA, objB) {
var result = 0;
for (var argIndex = 0; argIndex < sortArguments.length && result === 0; argIndex += 2) {
var propertyName = sortArguments[argIndex];
result = (objA[propertyName] < objB[propertyName]) ? -1 : (objA[propertyName] > objB[propertyName]) ? 1 : 0;
result *= sortArguments[argIndex + 1] ? 1 : -1;
}
return result;
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<th>Section #</th>
<th>Group #</th>
<th>Averages</th>
<th>Place</th>
</tr>
<tr>
<td class="class_section_number">1</td>
<td class="group_number">2</td>
<td class="grade">78.29</td>
<td>Test Place 1st</td>
</tr>
<tr>
<td class="class_section_number">1</td>
<td class="group_number">2</td>
<td class="grade">85.52</td>
<td>Test Place 1st</td>
</tr>
<tr>
<td class="class_section_number">1</td>
<td class="group_number">1</td>
<td class="grade">74.41</td>
<td>Test Place 2nd</td>
</tr>
<tr>
<td class="class_section_number">1</td>
<td class="group_number">2</td>
<td>No Data</td>
<td>Test Place 3rd</td>
</tr>
<tr><td class="class_section_number">2</td>
<td class="group_number">1</td>
<td class="grade">78.90</td>
<td>Test Place 2nd</td>
</tr>
</tr>
<tr><td class="class_section_number">1</td>
<td class="group_number">3</td>
<td class="grade">91.03</td>
<td>Test Place 2nd</td>
</tr>
</tr>
<tr><td class="class_section_number">2</td>
<td class="group_number">2</td>
<td class="grade">81.69</td>
<td>Test Place 2nd</td>
</tr>
<tr>
<td class="class_section_number">2</td>
<td class="group_number">2</td>
<td class="grade">81.13</td>
<td>Test Place 1st</td>
</tr>
<tr>
<td class="class_section_number">2</td>
<td class="group_number">2</td>
<td class="grade">78.13</td>
<td>Test Place 1st</td>
</tr>
</tbody>
</table>

Calculate sum of merged rows and display in third column

I am trying to calculate the monthly expenses from my table.
Want to sum up all the amount month wise and display in total like for January month total will be $180, March will be $230 and May $200. The amount should reflect in the total column. I have created this table using ng-repeat of angular framework (dynamic table)
JSFIDDLE
I have tried below code which will sum up all the individual cols having only numeric values. This code is not working for merged rows.
for (col = 1; col < ncol + 1; col++) {
console.log("column: " + col);
sum = 0;
$("tr").each(function(rowindex) {
$(this).find("td:nth-child(" + col + ")").each(function(rowindex) {
newval = $(this).find("input").val();
console.log(newval);
if (isNaN(newval)) {
$(this).html(sum);
} else {
sum += parseInt(newval);
}
});
});
}
});
Any help on this will be really helpful.
I would add a data-month attribute to the cell displaying the amount, it is not visible to users, but super helpful for you. Have a look at the solution below.
function getMonth(month) {
var monthCells = $("td[data-month='" + month + "']"); // get all TDs with a data month attribute
var sum = 0;
for(var i = 0; i < monthCells.length; i++){ // iterate over the tds
var amountCell = monthCells[i]; // get a td for given iteration
var amountCellText = $(amountCell).text(); // get the text content
sum += parseInt(amountCellText.replace(/\D/, "")); // in amoutnCellText replace anything that's not a digit into an empty string
}
return sum;
}
console.log(getMonth("march"))
table, th, td {
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>Month</th>
<th>Savings</th>
<th>Total</th>
</tr>
<tr>
<td rowspan="2">January</td>
<td data-month="january">$100</td>
</tr>
<tr>
<td data-month="january">$80</td>
</tr>
<tr>
<td rowspan="2">March</td>
<td data-month="march">$200</td>
</tr>
<tr>
<td data-month="march">$30</td>
</tr>
<tr>
<td>May</td>
<td data-month="may">$200</td>
</tr>
</table>
How about something like this?
vm.data = [
{
month: 'January',
savings: [
{ amount: 100 },
{ amount: 200}
]
},
{
month: 'February',
savings: [
{ amount: 300 },
{ amount: 400 }
]
}
];
In html:
<table class="table table-bordered table-condensed">
<tr>
<th>Month</th>
<th>Savings</th>
<th>Total</th>
</tr>
<tr ng-repeat="row in vm.data">
<td>{{row.month}}</td>
<td>
<table class="table table-bordered table-condensed">
<tr ng-repeat="s in row.savings">
<td>${{s.amount}}</td>
</tr>
</table>
</td>
<td>${{vm.getTotal(row.savings)}}</td>
</tr>
</table>
In JS:
vm.getTotal = getTotal;
function getTotal(savings) {
var total = 0;
angular.forEach(savings,
function (row) {
total += row.amount;
});
return total;
}
The key here is data modeling so that you have a simple function in getting total. Hope it will help.
Sample

Getting the sum and average in javascript

How to get the sum and average of the last column.In my code it wont get the correct value if the table has one,two and three rows.This works only on table with 4 rows.I know something wrong with my code but i cant figure it out how the loop works within .each function.
Important note:this runs with keyup event to update table data.Its not just a display.To be exact it is an update form.
Desired output
Item | value1 | value 2 | value3 |value 4 | Average
01 90 88 87 80 82.25
Total average 82.25 result of 82.25/1 number of row
if two rows
Item | value1 | value 2 | value3 |value 4 | Average
01 90 88 87 80 82.25
02 80 85 86 84 83.75
Total average 83 result of (82.25+83.75)/2 number of rows
But the result comes out with multiple loops
Here is the console.log(totalAverage)
86.25
176
264.75
353.5
442.25
86.25
176
264.75
353.5
442.25
Problem:How to suppress or skip this unnecessary values.I only need the 86.25 to display in total-ave.Note: this is only single row right now and have already incountered this miscaculation, how much more if the table has multiple rows then?
Html
<tr>
<th colspan="12"><h4>Card</h4></th>
</tr>
<tr>
<th colspan="3">Subjects</th>
<th colspan="2">First Grading</th>
<th colspan="2">Second Grading</th>
<th colspan="2">Third Grading</th>
<th colspan="2">Fourth Grading</th>
<th>Average</th>
</tr>
</thead>
<tbody>
#foreach($update_card['AllGrade'] as $subject)
{!! Form::hidden('grade_id[]',$subject['grade_id']) !!}
<tr>
<th colspan="3">{!! $subject->subject !!}</th>
<td colspan="2">{!! Form::text('term_1[]',$subject->term_1,['class'=>'form-control','name[]'=>'term_1','id[]'=>'term_1','value'=>'0']) !!}</td>
<td colspan="2">{!! Form::text('term_2[]',$subject->term_2,['class'=>'form-control','name[]'=>'term_2','id[]'=>'term_2','value'=>'0']) !!}</td>
<td colspan="2">{!! Form::text('term_3[]',$subject->term_3,['class'=>'form-control','name[]'=>'term_3','id[]'=>'term_4','value'=>'0']) !!}</td>
<td colspan="2">{!! Form::text('term_4[]',$subject->term_4,['class'=>'form-control','name[]'=>'term_4','id[]'=>'term_4','value'=>'0']) !!}</td>
<td colspan="2" class="average" id="average" value="0"> Average</td>
</tr>
#endforeach
<tr>
<th colspan="11">Total Average:</th>
<th>{!! Form::text('scholar_GPA',$update_card->scholar_GPA,['class'=>'form-control total-ave','name' => 'total-ave','id' => 'total-ave','value' => '0']) !!}</th>
</tr>
Javascript snippet
$("input").on("keyup", function(){
$("tbody tr").each(function() {
var col=1;
var tr =1;
var t = 0;
var a = 0;
$(this).children('td').not(':last').each(function () {
var number = ($(this).children('input').length == 0) ? $(this).html() : $(this).children('input').first().val();
// console.log(number);
// console.log(col);
t += parseInt(number);
// console.log(t);
a = t/col;
col++;
});
$(this).children('td').last().html(a);//last td of the row
// console.log(a);
col=1;
tr++;
});
calcTotalave();
});
// calculate total average
function calcTotalave() {
var totalAve = 0;
var tot=0;
var c = 2;
var count =0;
$( ".average" ).each(function() {
// console.log($(this).html());
var thisAve = parseFloat($(this).html());
if(!thisAve || thisAve === NaN || thisAve == "") {
thisAve = 0;
}
totalAve += thisAve;
//alert('count'+thisAve+totalAve);
console.log(totalAve);
count++;
});
c++;
totalAve = totalAve/c;
// console.log(totalAve);
$("#total-ave").val(totalAve);
}
UPDATED: fiddle below with comments, press space-bar to run, based around the below function.
the fiddle is made to cycle through and calc cells by row, so no .average class required. You will need to adapt it for your html table layouts as per your database output.
calcTotalave();
});
// calculate total average
function calcTotalave() {
var totalAve = 0;
$( ".average" ).each(function() {
var thisAve = parseFloat($(this).text()) || 0; // always return a number
totalAve += thisAve;
});
var Aver = totalAve / $('.average').length;
console.log(totalAve);
$("#total-ave").text(Aver);
}
instead of classing each cell as .average you could use the selector to target all the cells td of a given row:
$('input').change(function() {
calTotalAverages(); // the magic and collect the total average
});
function calTotalAverages(){
var SumAve = 0, nums = 0; // to collect total averages and the number of rows
$('tr').each(function(i) {
if (i > 0) { // ignore the first row
var $this = $(this);
SumAve += calcRowAve($this); // add up the returned averages and run the function
nums ++; // count the rows
}
}); // cycle through each row
var sum = (SumAve / nums);
$('#total-ave').text(sum.toFixed(2)); // display the total average
return sum; // return the total average
}
// calculate total average
function calcRowAve(targetRow) {
var totalAve = 0,
targetCells = targetRow.children(),
targLength = targetCells.length - 2; // total number of values in a row
targetCells.each(function(i) {
if (i > 0 && i <= targLength) {
var thisAve = parseFloat($('input',this).val()) || parseFloat($(this).text()) || 0; // always return a number
totalAve += thisAve;
} // check to ignore the first cell and the last
});
var Aver = totalAve / targLength; // get the average
targetCells.last().text(Aver); // update the last cell of the row
return Aver; // return the average for this row
}
#total-ave {
position: fixed;
right: 2em;
top: 8em;
}
input{
width: 5em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>item 1</th>
<th>value 1</th>
<th>value 2</th>
<th>value 3</th>
<th>value 4</th>
<th>average</th>
</tr>
<tr>
<td>1</td>
<td>90</td>
<td>88</td>
<td>87</td>
<td>80</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td>80</td>
<td>85</td>
<td>86</td>
<td>84</td>
<td></td>
</tr>
<tr>
<td>3</td>
<td><input type='number'></td>
<td><input type='number'></td>
<td><input type='number'></td>
<td><input type='number'></td>
<td></td>
</tr>
</table>
<div id='total-ave'></div>

Knockout.js - Sum table, add row and fill the table with AJAX

Im using this table to add materials and using Knockoutjs-3.4.0.js to add row and to sum it. My problem is when i try to edit the code i want to populate the table with a AJAX request. The problem is that i don't know how to fill the table with the AJAX response.
If i use the code below i get this error:
ReferenceError: Unable to process binding "click: function (){return
addMaterial }" Message: Can't find variable: addMaterial
<table class="table table-bordered">
<thead>
<tr>
<th>Moment</th>
<th>Antal </th>
<th>Kostnad</th>
<th>Totalt</th>
<th></th>
</tr>
</thead>
<tbody data-bind="foreach: materials">
<tr>
<td><input data-bind="value: name" /></td>
<td><input data-bind="value: quantity" /></td>
<td><input data-bind="value: rate" /></td>
<td data-bind="text: formattedTotal"></td>
<td></td>
</tr>
<tfoot>
<tr>
<th colspan="2"><button class="fa fa-plus btn-success" data-bind="click: addMaterial, enable: materials().length < 20"> Lägg till rad</button></th>
<th class="text-right">Totalt</th>
<th class="text-center"><span data-bind="text: totalSurcharge().toFixed(0)"></span></th>
<th> </th>
</tr>
<tr id="momsRow" class="hidden">
<th colspan="3" class="text-right">Moms</th>
<th class="text-center"><span data-bind="text: totalVat().toFixed(1)"></span></th>
<th> </th>
</tr>
<tr id="byggmomsRow" class="hidden">
<th colspan="3" class="">Omvänd byggmoms</th>
<th class="text-center"></th>
<th> </th>
</tr>
<tr>
<th colspan="3" class="text-right">Totalt:</th>
<th class="text-center"><span data-bind="text: totalPlusVat().toFixed(2)"></span></th>
<th> </th>
</tr>
</tfoot>
</tbody>
</table>
The knockout.js code:
/*------------- Load rows ------------- */
function LoadRows() {
var self = this;
self.materials = ko.observableArray([]);
$.getJSON("/json/tender_offer_edit_moment_json.asp", function(data) {
self.materials(data);
})
}
//ko.applyBindings(new dealModel());
ko.applyBindings(new LoadRows());
/*------------- Sum table ------------- */
function addMaterial() {
this.name = ko.observable("");
this.quantity = ko.observable("");
this.rate = ko.observable(0);
this.formattedTotal = ko.computed(function() {
return this.rate() * this.quantity();
}, this);
}
function documentViewModel(){
var self = this;
//create a materials array
self.materials = ko.observableArray([
new addMaterial()
]);
// Computed data
self.totalSurcharge = ko.computed(function() {
var total = 0;
for (var i = 0; i < self.materials().length; i++)
total += self.materials()[i].formattedTotal();
return total;
});
// add VAT(moms 25%) data
self.totalVat = ko.computed(function() {
var totalWithVat = 0;
for (var i = 0; i < self.materials().length; i++)
totalWithVat += self.materials()[i].formattedTotal();
totalWithVat = totalWithVat*0.25;
return totalWithVat;
});
// Totalt with VAT(moms 25%) data
self.totalPlusVat = ko.computed(function() {
var totalWithVat = 0;
for (var i = 0; i < self.materials().length; i++)
totalWithVat += self.materials()[i].formattedTotal();
totalWithVat = totalWithVat*1.25;
return totalWithVat;
});
// Operations
self.addMaterial = function() {
self.materials.push(new addMaterial());
}
self.removeMaterial = function(material) { self.materials.remove(material) }
}
ko.applyBindings(new documentViewModel());
/*------------- Sum table END ------------- */
There is a correct json format on the AJAX request.
[{"name":"Moment 1","quantity":"1","rate":"10","formattedTotal":"10"},{"name":"Moment 2","quantity":"2","rate":"20","formattedTotal":"40"}]
$.ajax({
url: "/json/tender_offer_edit_moment_json.asp",
type: "GET",
dataType: "json",
success: function (data) {
console.log(data);
alert(data);
//new addMaterial(data);
new addMaterial(data);
}
});
JsFiddle
First of all, you call ko.applyBindings() twice and to whole page,
it is not suitable in your situation:
To load the initial data you can do smth like this:
var vm = new documentViewModel();
$.getJSON("/json/tender_offer_edit_moment_json.asp", function(data) {
vm.materials(data);
})
ko.applyBindings(vm);
and delete this lines:
function LoadRows() {
var self = this;
self.materials = ko.observableArray([]);
$.getJSON("/json/tender_offer_edit_moment_json.asp", function(data) {
self.materials(data);
})
}
//ko.applyBindings(new dealModel());
ko.applyBindings(new LoadRows());

Click table row and get value of all cells

I don't know JQuery, so I'm hoping there is a way to do this in pure Javascript.
I need to click on a table row and get the value of each cell in that row. Here is the format of my table:
<table class='list'>
<tr>
<th class='tech'>OCB</th>
<th class='area'>Area</th>
<th class='name'>Name</th>
<th class='cell'>Cell #</th>
<th class='nick'>Nickname</th>
</tr>
<tr onclick="somefunction()">
<td>275</td>
<td>Layton Installation</td>
<td>Benjamin Lloyd</td>
<td>(801) 123-456</td>
<td>Ben</td>
</tr>
</table>
Is there anyway short of putting a unique ID to each cell?
There is no need to add ids or add multiple event handlers to the table. One click event is all that is needed. Also you should use thead and tbody for your tables to separate the heading from the content.
var table = document.getElementsByTagName("table")[0];
var tbody = table.getElementsByTagName("tbody")[0];
tbody.onclick = function (e) {
e = e || window.event;
var data = [];
var target = e.srcElement || e.target;
while (target && target.nodeName !== "TR") {
target = target.parentNode;
}
if (target) {
var cells = target.getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
data.push(cells[i].innerHTML);
}
}
alert(data);
};
<table class='list'>
<thead>
<tr>
<th class='tech'>OCB</th>
<th class='area'>Area</th>
<th class='name'>Name</th>
<th class='cell'>Cell #</th>
<th class='nick'>Nickname</th>
</tr>
</thead>
<tbody>
<tr>
<td>275</td>
<td>Layton Installation</td>
<td>Benjamin Lloyd</td>
<td>(801) 123-456</td>
<td>Ben</td>
</tr>
</tbody>
</table>
Example:
http://jsfiddle.net/ZpCWD/
Check this fiddle link
HTML:
<table id="rowCtr" class='list'>
<thead>
<tr>
<th class='tech'>OCB</th>
<th class='area'>Area</th>
<th class='name'>Name</th>
<th class='cell'>Cell #</th>
<th class='nick'>Nickname</th>
</tr>
</thead>
<tbody>
<tr>
<td>275</td>
<td>Layton Installation</td>
<td>Benjamin Lloyd</td>
<td>(801) 123-456</td>
<td>Ben</td>
</tr>
</tbody>
</table>
JAVASCRIPT:
init();
function init(){
addRowHandlers('rowCtr');
}
function addRowHandlers(tableId) {
if(document.getElementById(tableId)!=null){
var table = document.getElementById(tableId);
var rows = table.getElementsByTagName('tr');
var ocb = '';
var area = '';
var name = '';
var cell = '';
var nick = '';
for ( var i = 1; i < rows.length; i++) {
rows[i].i = i;
rows[i].onclick = function() {
ocb = table.rows[this.i].cells[0].innerHTML;
area = table.rows[this.i].cells[1].innerHTML;
name = table.rows[this.i].cells[2].innerHTML;
cell = table.rows[this.i].cells[3].innerHTML;
nick = table.rows[this.i].cells[4].innerHTML;
alert('ocb: '+ocb+' area: '+area+' name: '+name+' cell: '+cell+' nick: '+nick);
};
}
}
}
var elements = document.getElementsByTagName('td');
for (var i =0; i < elements.length; i++) {
var cell_id = 'id' + i;
elements[i].setAttribute('id', cell_id);
}
Maybe put something like this in function your onclick links to from the tr?
$("tr").click(function () {
var rowItems = $(this).children('td').map(function () {
return this.innerHTML;
}).toArray();
});
This shows the row's first cell which is clicked according to dataTr.querySelectorAll("td")[0].innerText;
document.querySelector("#myTable").addEventListener("click",event => {
let dataTr = event.target.parentNode;
let dataRes = dataTr.querySelectorAll("td")[0].innerText;
console.log(dataRes);
});

Categories

Resources