when I execute this code it spits out a new row inside the table but it includes the previous iteration along with the newest one. I want all "As" to be in the first row in the main table. And then I want all "Bs" to be in the second , etc, etc. Then for A0, A1, and A2, I want them to be in their own table within the first row, same for B0, B1 in the second row, etc, etc
<head>
<style>
table,
th,
td {
border: 1px solid black;
}
}
</style>
</head>
<table id="table">
<tr>
<td>gerp gerp</td>
<td>
<table id="0"></table>
</td>
</tr>
<tr>
<td>gerp gerp</td>
<td>
<table id="1"></table>
</td>
</tr>
<tr>
<td>gerp gerp</td>
<td>
<table id="2"></table>
</td>
</tr>
<tr>
<td>gerp gerp</td>
<td>
<table id="3"></table>
</td>
</tr>
</table>
<script>
var array = [
["A0---", "A1----", "A2---"],
["B0----", "B1---"],
["C0---", "C1---"],
["D0---", "D1---"]
];
var text = ""
console.log(array.length);
for (var i = 0; i < array.length; i++) {
var j = 0;
console.log(array[i].length);
while (j < array[i].length) {
text += "<tr><td>" + array[i][j] + "</td></tr>";
j++;
}
document.getElementById(i).innerHTML = text;
}
</script>
Initialize the text variable to the empty string inside the first loop instead:
for (var i = 0; i < array.length; i++) {
let text = '';
But note that you can make your code more functional, shorter, and easier to read by using array methods like .map and forEach rather than using for, while, and manual iteration (better not to have to keep track of indicies):
array.forEach((subArr, i) => {
const text = subArr.map(item => "<tr><td>" + item + "</td></tr>");
document.getElementById(i).innerHTML = text.join('');
});
var array = [
["A0---", "A1----", "A2---"],
["B0----", "B1---"],
["C0---", "C1---"],
["D0---", "D1---"]
];
array.forEach((subArr, i) => {
const text = subArr.map(item => "<tr><td>" + item + "</td></tr>");
document.getElementById(i).innerHTML = text.join('');
});
table,
th,
td {
border: 1px solid black;
}
<table id="table">
<tr>
<td>gerp gerp</td>
<td>
<table id="0"></table>
</td>
</tr>
<tr>
<td>gerp gerp</td>
<td>
<table id="1"></table>
</td>
</tr>
<tr>
<td>gerp gerp</td>
<td>
<table id="2"></table>
</td>
</tr>
<tr>
<td>gerp gerp</td>
<td>
<table id="3"></table>
</td>
</tr>
</table>
Declare this variable var text = ""; inside of the for-loop
var array = [ ["A0---", "A1----", "A2---"], ["B0----", "B1---"], ["C0---", "C1---"], ["D0---", "D1---"]];
for (var i = 0; i < array.length; i++) {
var text = "";
var j = 0;
while (j < array[i].length) {
text += "<tr><td>" + array[i][j] + "</td></tr>";
j++;
}
document.getElementById(i).innerHTML = text;
}
table,th,td { border: 1px solid black;}
<table id="table"> <tr> <td>gerp gerp</td> <td> <table id="0"></table> </td> </tr> <tr> <td>gerp gerp</td> <td> <table id="1"></table> </td> </tr> <tr> <td>gerp gerp</td> <td> <table id="2"></table> </td> </tr> <tr> <td>gerp gerp</td> <td> <table id="3"></table> </td> </tr></table>
Related
I am trying to add Price from table column to a total.
I am having problem adding values such as 10.00 or 5.99. I am able to calculate prices with int values, but not with values 10.00 or 5.99, etc.
Here is what I have below.
var table = document.getElementById("myTable"),
sumVal = 0;
for (var i = 1; i < table.rows.length; i++) {
sumVal = sumVal + parseF(table.rows[i].cells[2].innerHTML);
}
document.getElementById("val").innerHTML = "SubTotal =" + sumVal;
console.log(sumVal);
<table id="myTable">
<tr>
<th>Item</th>
<th>Price</th>
<th>Remove</th>
</tr>
<tr>
<td>Hoddie</td>
<td class="count-me">15.00</td>
<td><button onClick="myFunction()">Remove</button></td>
</tr>
<tr>
<td>Nike Cap</td>
<td class="count-me">10.99</td>
<td><button onClick="myFunction()">Remove</button></td>
</tr>
</table>
<span id="val"></span>
You have three issues:
You are grabbing the wrong cell index, indices start at 0:
table.rows[i].cells[1]
You need to call the correct parse function:
parseFloat(table.rows[i].cells[1].innerHTML);
You need to format your output:
"SubTotal = $" + sumVal.toFixed(2);
Update: Added functionality for removing rows.
updateSubTotal(); // Initial call
function updateSubTotal() {
var table = document.getElementById("myTable");
let subTotal = Array.from(table.rows).slice(1).reduce((total, row) => {
return total + parseFloat(row.cells[1].innerHTML);
}, 0);
document.getElementById("val").innerHTML = "SubTotal = $" + subTotal.toFixed(2);
}
function onClickRemove(deleteButton) {
let row = deleteButton.parentElement.parentElement;
row.parentNode.removeChild(row);
updateSubTotal(); // Call after delete
}
#myTable td {
padding: 0.25em;
}
#val {
display: block;
margin-top: 0.5em;
}
<table id="myTable">
<tr>
<th>Item</th>
<th>Price</th>
<th>Remove</th>
</tr>
<tr>
<td>Hoodie</td>
<td class="count-me">15.00</td>
<td><button onClick="onClickRemove(this)">Remove</button></td>
</tr>
<tr>
<td>Nike Cap</td>
<td class="count-me">10.99</td>
<td><button onClick="onClickRemove(this)">Remove</button></td>
</tr>
</table>
<span id="val"></span>
You are accessing the incorrect array element and also need to use parseFloat
The cells array is zero-based so you need to use cells[1] to access the second column:
var table = document.getElementById("myTable"),
sumVal = 0;
for (var i = 1; i < table.rows.length; i++) {
sumVal = sumVal + parseFloat(table.rows[i].cells[1].innerHTML);
}
document.getElementById("val").innerHTML = "SubTotal =" + sumVal;
console.log(sumVal);
<table id="myTable">
<tr>
<th>Item</th>
<th>Price</th>
<th>Remove</th>
</tr>
<tr>
<td>Hoddie</td>
<td class="count-me">15.00</td>
<td><button onClick="myFunction()">Remove</button></td>
</tr>
<tr>
<td>Nike Cap</td>
<td class="count-me">10.99</td>
<td><button onClick="myFunction()">Remove</button></td>
</tr>
</table>
<span id="val"></span>
updateSubTotal(); // Initial call
function updateSubTotal() {
var table = document.getElementById("myTable");
let subTotal = Array.from(table.rows).slice(1).reduce((total, row) => {
return total + parseFloat(row.cells[1].innerHTML);
}, 0);
let subTotal2 = Array.from(table.rows).slice(1).reduce((total, row) => {
return total + parseFloat(row.cells[2].innerHTML);
}, 0);
document.getElementById("val").innerHTML = "SubTotal = $" + subTotal.toFixed(2);
document.getElementById("val1").innerHTML = subTotal2.toFixed(2);
}
function onClickRemove(deleteButton) {
let row = deleteButton.parentElement.parentElement;
row.parentNode.removeChild(row);
updateSubTotal(); // Call after delete
}
#myTable td {
padding: 0.25em;
}
#val {
display: block;
margin-top: 0.5em;
}
<table id="myTable">
<tr>
<th>Item</th>
<th>Price</th>
<th>M2</th>
<th>Remove</th>
</tr>
<tr>
<td>Hoodie</td>
<td class="count-me">15.00</td>
<td class="count-me">34.00</th>
<td><button onClick="onClickRemove(this)">Remove</button></td>
</tr>
<tr>
<td>Nike Cap</td>
<td class="count-me">10.99</td>
<td class="count-me">22.34</th>
<td><button onClick="onClickRemove(this)">Remove</button></td>
</tr>
</table>
<span id="val"></span>
<span id="val1"></span>
var cell = document.getElementsByClassName("count-me");
var val = 0;
var i = 0;
while (cell[i] != undefined) {
val += parseFloat(cell[i].innerHTML);
i++;
} //end while
document.getElementById("val").innerHTML = parseFloat(val).toFixed(2);
console.log(parseFloat(val).toFixed(2));
<table id="myTable">
<tr>
<th>Item</th>
<th>Price</th>
<th>Remove</th>
</tr>
<tr id="">
<td>Hoddie</td>
<td class="count-me">15.00</td>
<td>
<button onClick="myFunction()">Remove</button>
</td>
</tr>
<tr>
<td>Nike Cap</td>
<td class="count-me">10.99</td>
<td>
<button onClick="myFunction()">Remove</button>
</td>
</tr>
</table>
<span id="val"></span>
<table>
<tr>
<td id="1">Adi</td>
<td id="2">Aman</td>
</tr>
</table>
In the above code, I want to know the position of Aman using its id
You can try something like this:
html:
<table id="myTable">
<tr>
<td id="1">Adi</td>
<td id="2">Aman</td>
</tr>
</table>
js:
function getIdFromTable(searchValue)
{
var t = document.getElementById("myTable");
var trs = t.getElementsByTagName("tr");
var tds = null;
for (var i=0; i<trs.length; i++)
{
tds = trs[i].getElementsByTagName("td");
for (var n=0; n<tds.length;n++)
{
if (tds[n].innerText === searchValue) {
return tds[n].id;
}
}
}
}
getIdFromTable('Aman'); // will return 2
Easiest way to find position by id would be using prevAll().length. Something like this:
function findPositionById(id){
return $('#mytable').find('#'+id).prevAll().length
}
console.log('Adi Position', findPositionById(1));
console.log('Aman Position', findPositionById(2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<table id="mytable">
<tr>
<td id="1">Adi</td>
<td id="2">Aman</td>
</tr>
</table>
Remove dynamically loaded tooltips table tr
I have charts so each charts bar have tooltips its shows to value previous bar value and current hover bar value so i want to hide the tr if the text NA in td. i have done below code but its not working
<div class="customTooltipRapsure">
<div class="scrollingTooltip">
<table id="tooltipTable">
<tbody>
<tr class="OldGrossBudget">
<td>Old Gross Budget </td>
<td>NA</td>
</tr>
<tr class="NewGrossBudget">
<td>New Gross Budget </td>
<td class="text-right">9,964.72</td></tr>
</tbody>
</table>
</div>
</div>
$(document).ready(function () {
$(".customTooltipRapsure #tooltipTable tbody tr td").filter(function () {
return $(this).text() === "NA";
}).closest("tr").remove();
});
You may remove NA td using javascript
function removeTR(){
var tableToolTip = document.getElementById('tooltipTable');
const table = document.getElementById('tooltipTable').getElementsByTagName('tr');
for (let x = 0; x < table.length; x++) {
const row = table[x];
const tds= row.getElementsByTagName("td");
for (let y = 0; y < tds.length; y++) {
if (tds[y].innerText == "NA") {
table[x].remove();
break;
}
}
}
}
removeTR();
<div class="customTooltipRapsure">
<div class="scrollingTooltip">
<table id="tooltipTable">
<tbody>
<tr class="OldGrossBudget">
<td>Old Gross Budget </td>
<td>NA</td>
</tr>
<tr class="NewGrossBudget">
<td>New Gross Budget </td>
<td class="text-right">9,964.72</td></tr>
</tbody>
</table>
</div>
</div>
i am not sure using filter to find column with text "NA" , so i use another method
const table = $("#tooltipTable tbody tr")
for (let x = 0; x < table.length; x++) {
const row = $("#tooltipTable tbody").find(`tr:eq(${x})`)
for (let y = 0; y < row.find("td").length; y++) {
if (row.find(`td:eq(${y})`).text() == "NA") {
row.find(`td:eq(${y})`).closest("tr").remove();
}
}
}
table {
border: solid 2px black;
}
td {
border: solid 1px black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="customTooltipRapsure">
<div class="scrollingTooltip">
<table id="tooltipTable">
<tbody>
<tr class="OldGrossBudget">
<td>Old Gross Budget </td>
<td>NA</td>
</tr>
<tr class="NewGrossBudget">
<td>New Gross Budget </td>
<td class="text-right">9,964.72</td>
</tr>
</tbody>
</table>
</div>
</div>
first you need to loop total row , then loop total column finally find column with text "NA"
hope this will solve your problem
for (var i = 0; i < 10; i++) {
var tr = $("<tr></tr>")
tr.append("<td>1</td>");
tr.append("<td>2</td>");
$("table tbody").append(tr)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody></tbody>
</table>
How Can I append rows and then dynamically change the rowspan of every second row. What I want to happend is it will look like below:
<table border='1'>
<tbody>
<tr>
<td rowspan="2">1</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
</tr>
<tr>
<td rowspan="2">1</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
</tr>
<tr>
<td rowspan="2">1</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
</tr>
<tr>
<td rowspan="2">1</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
</tr>
<tr>
<td rowspan="2">1</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
</tr>
</tbody>
</table>
I tried using index but it is not adding the rowspan
Any help is appreciated.
FYI : What I want to happened is append first then change the row span after the row is appended
Just added mod (%)
for (var i = 0; i < 10; i++) {
var tr = $("<tr></tr>");
if(i%2===0){
tr.append("<td rowspan='2'>1</td>");
}
tr.append("<td>2</td>");
$("table tbody").append(tr)
}
td, th {
border: 1px solid #ddd;
padding: 8px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<table>
<tbody></tbody>
</table>
</body>
</html>
I hope I achieve what you need.
I base the result from your second snippet.
for (var i = 0; i < 10; i++) {
var tr = $("<tr></tr>")
tr.append("<td>1</td>");
tr.append("<td>2</td>");
$("table tbody").append(tr)
}
$('button').click(function(){
$('table tr:odd td:first-child').remove();
$('table tr:even td:first-child').attr('rowspan', 2);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1">
<tbody></tbody>
</table>
<button>append</button>
try to use html string and then attach it to your element and make the rowspan dynamic for example :
var html_string = '<tr>'
for (var i = 0; i < 10; i++) {
html_string+= '<td rowspan="'+i+'">1</td>'
html_string += '<td>2</td>'
}
html_string +='</tr>'
$("table tbody").append(html_string)
Below code may help,
for (var i = 0; i < 10; i++) {
var tr = $("<tr></tr>");
tr.append("<td>1</td>");
tr.append("<td>2</td>");
$("table tbody").append(tr)
}
$('table tr:odd td:first-child').remove();
$('table tr:even td:first-child').attr('rowspan', 2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border='1'>
<tbody></tbody>
</table>
Good Evening, i want to get all the data from the row that the user clicks on, so i tried this script, it gets the row id but it doesn't get the data exists in that row, i push every data in that row to an array for further uses:
function findRowNumber() {
var rowIdx;
var rowData = new Array();
var table = document.getElementById('product_table');
var rows = table.getElementsByTagName('tr');
var selectedRow;
var rowCellValue;
for (i = 0; i < rows.length; i++) {
rows[i].onclick = function() {
rowIdx = this.rowIndex;
selectedRow = rows[rowIdx];
for (j = 1; j < selectedRow.length; j++) { // it doesn't enter that loop
rowCellValue = selectedRow.cells[j].value;
rowData.push(rowCellValue);
alert("Value " + rowCellValue);
}
}
}
}
selectedRow is populated after you click the row, while you are trying to loop trough it after binding the click handler, but before the actual click. You have to move that code in the click handler
If the data in the cells is text,
it may be simpler to retrieve with textContent(or innerText).
<!doctype html>
<html lang= "en">
<head>
<meta charset= "utf-8">
<title> Small Test Page</title>
<style>
table{border:3px ridge #c0c0c0;border-collapse:collapse;}
th, td{border:1px solid black}
</style>
<script>
function findRowNumber(){
var rowIdx;
var rowData= [];
var table= document.getElementById('product_table');
var rows= table.getElementsByTagName('tr');
var selectedRow;
var rowCellValue;
for(i= 0;i<rows.length;i++){
rows[i].onclick= function(){
rowIdx= this.rowIndex;
selectedRow= this.cells;
for(j= 0;j<selectedRow.length;j++){
rowCellValue= selectedRow[j].textContent ||
selectedRow[j].innerText;
rowData.push('cell '+j+': '+rowCellValue);
}
alert("Row #" +rowIdx+'. '+ rowData);
}
}
}
</script>
</head>
<body>
<h1> Retrieve Row Data</h1>
<p> <button type= "button" id= "tableSwapBtn" onclick= "findRowNumber()">
Click to initialize</button> </p>
<table id="product_table" style="width:300px">
<tbody>
<tr> <td> a</td> <td> 1</td> </tr>
<tr> <td> b</td> <td> 2</td> </tr>
<tr> <td> c</td> <td> 3</td> </tr>
<tr> <td> d</td> <td> 4</td> </tr>
<tr> <td> e</td> <td> 5</td> </tr>
<tr> <td> f</td> <td> 6</td> </tr>
<tr> <td> g</td> <td> 7</td> </tr>
</tbody>
</table>
</body>
</html>