I want to show my xy coordinates in html td cell using JavaScript but instead of showing an alert, I want it to be shown in an html textbox
var table = document.getElementsByTagName("table")[0];
var cells = table.getElementsByTagName("td"); //
for(var i = 1; i < cells.length; i++){
var cell = cells[i];
cell.onclick = function(){
var cellIndex = this.cellIndex + 1;
var rowIndex = this.parentNode.rowIndex + 1;
alert("X: " + cellIndex + " / Y: " + rowIndex );
}
}
I have loop over the td elements and bind click event.So each time you click on td you will see cellIndex and rowIndex.Check my code and let me know if it satisfies you.
var cells = document.querySelectorAll("table td");
for(var i = 0; i < cells.length; i++){
cells[i].addEventListener('click',showCoordinates);
}
function showCoordinates(){
var cellIndex = this.cellIndex + 1;
var rowIndex = this.parentNode.rowIndex + 1;
this.innerHTML = "X:"+cellIndex +" Y:"+rowIndex;
}
table td{ padding:10px; }
<table border="1">
<tr>
<td>TD</td>
<td>TD</td>
<td>TD</td>
</tr>
<tr>
<td>TD</td>
<td>TD</td>
<td>TD</td>
</tr>
</table>
There are different ways to achieve what I think you want. Feel free to update you question to reflect your will. Adding your HTML as inquired in comment, would be useful.
Lets assume that your table doesn't use rowspan or colspan. Something like this:
<table border="1">
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
The basic way with two loops:
// Lets get all your rows
var rows = document.querySelectorAll("table tr");
// for each row...
for (var j = 0; j < rows.length; j++) {
var row = rows[j];
// ... we will find all this rows' cells.
var cells = row.querySelectorAll("td");
// for each cell...
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
// ... we will set its textContent to its coordinate in the table
cell.textContent = "X: " + (i + 1) + " / Y: " + (j + 1);
}
}
<table border="1">
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
Another solution if you know beforehand the number of columns:
var colsCount = document.querySelectorAll("table tr:nth-child(1) td").length;
var cells = document.querySelectorAll("table td");
for (var i = 0; i < cells.length; i++) {
const y = i / colsCount | 0;
const x = i % colsCount;
cells[i].textContent = `X: ${x + 1} / Y: ${y + 1}`;
}
<table border="1">
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
Related
Using jquery or javascript, I'd like to get that how many element 500 in each column (1-4) of an html table is ? How should I do it ?
<html>
<table>
<thead>
<tr>
<th>Column-1</th>
<th>Column-2</th>
<th>Column-3</th>
<th>Column-4</th>
</tr>
</thead>
<tbody>
<tr>
<td>500</td>
<td>200</td>
<td>500</td>
<td>200</td>
</tr>
<tr>
<tr>
<td>501</td>
<td>500</td>
<td>500</td>
<td>200</td>
</tr>
</tbody>
</table>
</html>
The table is look like this format:
Column-1 Column-2 Column-3 Column-4
500 200 500 200
501 500 500 500
... ... .... ...
I would like to get : column-1: 1, column-2:1, column-3:2 column-4: 1
automatic display the numbers of "500" of each column .
Solution
filter the 's in row out
Store the column when the text of a td is 500
Count how often the column occurs
let trArr = $("table tr")
let res = [];
for (let i = 0; i < trArr.length; i++) {
let childs = trArr[i].children;
for (let j = 0; j < childs.length; j++) {
if(childs[j].tagName !== "TH"){
if (childs[j].textContent === "500" ) {
res.push({
"column": j+1
});
}
}
}
}
let result = new Set();
for (let i = 0; i < res.length; i++) {
let counter = 0;
for (let j = 0; j < res.length; j++) {
if (res[i].column === res[j].column) {
counter++;
}
}
result.add(`Column ${[res[i].column]}: ${counter} x 500`);
}
let resString = "";
for(let i of result){
resString += i + "\n";
}
document.getElementById("BLA").innerHTML = resString;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<table>
<thead>
<tr>
<th>Column-1</th>
<th>Column-2</th>
<th>Column-3</th>
<th>Column-4</th>
</tr>
</thead>
<tbody>
<tr>
<td>500</td>
<td>200</td>
<td>500</td>
<td>200</td>
</tr>
<tr>
<tr>
<td>501</td>
<td>500</td>
<td>500</td>
<td>200</td>
</tr>
</tbody>
</table>
<p id="BLA"></p>
</html>
My HTML table has some classes and table tag is used
Want to retain the classes as is, but all my table and tr , th or td are using td bgcolor which is an old technique.
I want to loop over the table and find if that bgcolor is defined, use the same color and convert it to a css based background color so i can print it in IE
function setBackground() {
var table = document.getElementById("table1");
//i found this in a previous stack overflow answer and tried it
for (var i = 0, row; row = table.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
//this is for debugging purposes... I can't even get this to work
alert(table.rows[i].cells[j]);
table.rows[i].cells[j].style.background = "orange"; //just an example
}
}
}
because IE is not able to print the background lines and colors for some reason using the webkit property
I cleaned up the for loops a little. You can read the attribute with getAttribute and set the style.
var table = document.getElementById("table1");
for (var i = 0; i < table.rows.length; i++) {
var row = table.rows[i]
for (var j = 0; j < row.cells.length; j++) {
var cell = row.cells[j]
var bgc = cell.getAttribute('bgcolor')
if (bgc) {
cell.style.background = bgc
}
}
}
td {
width: 30px; height: 30px;
}
<table id="table1">
<tr>
<td bgcolor="red"></td>
<td></td>
<td bgcolor="blue"></td>
</tr>
<tr>
<td></td>
<td bgcolor="green"></td>
<td></td>
</tr>
<tr>
<td bgcolor="yellow"></td>
<td></td>
<td></td>
</tr>
<tr>
<td bgcolor="silver"></td>
<td></td>
<td></td>
</tr>
</table>
You can just do it with one loop with getElementsByTagName
var tds = document.getElementById("table1").getElementsByTagName("td");
for (var i = 0; i < tds.length; i++) {
var cell = tds[i]
var bgc = cell.getAttribute('bgcolor')
if (bgc) {
cell.style.background = bgc
}
}
td {
width: 30px; height: 30px;
}
<table id="table1">
<tr>
<td bgcolor="red"></td>
<td></td>
<td bgcolor="blue"></td>
</tr>
<tr>
<td></td>
<td bgcolor="green"></td>
<td></td>
</tr>
<tr>
<td bgcolor="yellow"></td>
<td></td>
<td></td>
</tr>
<tr>
<td bgcolor="silver"></td>
<td></td>
<td></td>
</tr>
</table>
Get the color if found and then do with it whatever needed...
function setBackgroundColor(colorValue) {
const table = document.getElementById("table1");
const rows = table.children[0].rows
for (let i = 0; i < rows.length; i++) {
const tds = rows[i].children;
for (let j = 0; j < tds.length; j++) {
if (tds[j].bgColor === colorValue) {
console.log('Color found, do action')
}
}
}
}
setBackgroundColor('red')
<table id="table1">
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td bgcolor="red">January</td>
<td bgcolor="green">$100</td>
</tr>
</table>
You can do this:
var cells = $("#targetTable td");
for(i in cells){
color = $(cells[i]).attr('bgcolor');
console.log(color);
$(cells[i]).css({background: color});
}
as Taplar mentioned in the comment :
Use document.querySelectorAll('td[bgcolor]') to get the td that have bgcolor, loop through them and set the background to that color :
document.querySelectorAll('td[bgcolor]').forEach(e => {
const bgColor = e.getAttribute('bgcolor');
e.removeAttribute('bgcolor'); // optional, if you want to remove the attribute
e.style.background = bgColor;
})
<table id="table1">
<thead>
<th>A</th>
<th>B</th>
<th>C</th>
</thead>
<tbody>
<tr>
<td bgcolor="red">1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td bgcolor="green">5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td bgcolor="blue">9</td>
</tr>
</tbody>
</table>
How to add a table row or table column at specific index by on clicking the table cells, same as excel sheet.
<table >
<tr>
<th></th>
<th></th>
<th></th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
Add Row Script:
function AppendRows() {
var tableRows = document.getElementById('myTable'),
row = tableRows.insertRow(tableRows.rows.length);
row.height = '50';
for (var i = 0; i < tableRows.rows[0].cells.length; i++) {
row.insertCell(i), i, 'row';
}
}
Here is an example on how you can insert a new row. There are several approaches you can go with but basically this is the way
function insertrow() {
var newRowIndex = 1;
var row1 = document.getElementById("table").childNodes[1].childNodes[newRowIndex];
var newRow = document.createElement("tr");
var col0 = document.createElement("td");
col0.innerHTML = "newA";
newRow.appendChild(col0);
var col1 = document.createElement("td");
col1.innerHTML = "newB";
newRow.appendChild(col1);
var col2 = document.createElement("td");
col2.innerHTML = "newC";
newRow.appendChild(col2);
row1.parentNode.insertBefore(newRow, row1);
}
<button onclick="insertrow()">Insert row</button>
<table id="table">
<tr>
<td>a</td>
<td>b</td>
<td>c</td>
</tr>
<tr>
<td>d</td>
<td>e</td>
<td>f</td>
</tr>
</table>
Also i'd suggest you take a look at the insertBefore documentation.
Here's a method to insert a row after a row is clicked. The new row is added immediately after the clicked row, so new rows can be added at different locations.
Let's walk through it:
First we setup an event listener on the table to listen for clicks on the row elements. When a row is clicked, we call the the appendRow method to add a new row, and pass the index where we want the row to appear.
We're using delegation here so dynamically added rows will be included in the event listener.
The appendRow method adds a new row at the defined index, then adds a few table cells for presentation purposes.
var tableEl = document.getElementById('table');
tableEl.addEventListener('click', function(event) {
var el = event.target;
if (el.closest('tr') && el.closest('tbody')) {
var trow = el.parentElement;
var tbody = trow.parentElement;
var index = Array.prototype.indexOf.call(tbody.children, trow);
appendRow(tbody, index + 1);
}
});
function appendRow(tbody, index) {
var row = tbody.insertRow(index);
var cells = ['A', 'B', 'C'];
cells.forEach(function(cell, idx) {
var newCell = row.insertCell(idx);
var newText = document.createTextNode(`Row ${index} - ${cell}`);
newCell.appendChild(newText);
});
}
table {
table-layout: fixed;
width: 100%;
}
td {
border: 1px solid gray;
}
<table id="table">
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
</tr>
</tbody>
</table>
Lets say we have an Array that looks like this
(example)
Array1 = [Data_A,Data_B];
Array2 = [Data_1,Data_2,Data_3];
and I have a table that looks like this
How can I achieve this?
For now I can retreive the data in row order using for loop and this is my code
for (i = 0; i < Array1 .length; i++) {
for (x in Array1 [i]) {
console.log(data from array);
}
}
My target here is for every array is I need to make it as a row for every col. for example Array1 is fol Col1 and also note that my arrays are fixed for each col. col3 and 4 are for ex. only
Because the data in table columns don't usually change unlike they do in rows, I highly discourage managing table data by columns. It is best to do it by rows.
What I mean is to have Row1 = [Data_A, Data_1]; and Row2 = [Data_B, Data_2]; and so on, rather than how you had it set up.
function CreateRow(data) {
var tr = "<tr>"
for (var i = 0; i < data.length; i++) {
tr += "<td>" + data[i] + "</td>";
}
tr += "</tr>"
$('#table').append(tr);
}
function EditRow(data, rowIdx) {
var tr = $('#table').children().eq(0);
for (var i = 0; i < data.length; i++) {
tr.children().eq(i).text(data[i]);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
<th>Col4</th>
</tr>
</thead>
<tbody id="table">
<tr>
<td>Data 0</td>
<td>Data 1</td>
<td>Data 2</td>
<td>Data 3</td>
</tr>
</tbody>
</table>
<button type="button" onclick="CreateRow(['A','B','C','D'])">Create Row</button>
<button type="button" onclick="EditRow(['EditedData1','EditedData2', 'EditedData3', 'EditedData4'], 0)">Edit First Row</button>
(Pure Javascript snippet for those who are interested)
function CreateRow(data) {
var table = document.getElementById("table");
var tr = document.createElement("tr");
for (var i = 0; i < data.length; i++) {
var td = document.createElement("td");
td.appendChild(document.createTextNode(data[i]));
tr.appendChild(td);
}
table.appendChild(tr);
}
function EditRow(data, rowIdx) {
var tr = document.getElementById("table").getElementsByTagName("tr")[rowIdx];
for (var i = 0; i < data.length; i++) {
tr.getElementsByTagName("td")[i].innerHTML = data[i];
}
}
<table>
<thead>
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
<th>Col4</th>
</tr>
</thead>
<tbody id="table">
<tr>
<td>Data 0</td>
<td>Data 1</td>
<td>Data 2</td>
<td>Data 3</td>
</tr>
</tbody>
</table>
<button type="button" onclick="CreateRow(['A','B','C','D'])">Create Row</button>
<button type="button" onclick="EditRow(['EditedData1','EditedData2', 'EditedData3', 'EditedData4'], 0)">Edit First Row</button>
I have a table and I am editing the name of a specific table column value using the code below in JS:
document.querySelector('tr:nth-child(1) > td:nth-child(1)').innerHTML = "1111";
Now, I am trying to make it more dynamic considering that the column is unknown (first or third etc).
The script below check for every td in the table and it works:
var columns = document.getElementsByTagName('td');
for (var i=1; i<columns.length; i++)
{
if(document.querySelector('tr:nth-child(1) > td:nth-child('+i+')').innerHTML.includes("Column 1"))
{
document.querySelector('tr:nth-child(1) > td:nth-child('+i+')').innerHTML = "11111";
}
if(document.querySelector('tr:nth-child(1) > td:nth-child('+i+')').innerHTML.includes("Column 2"))
{
document.querySelector('tr:nth-child(1) > td:nth-child('+i+')').innerHTML = "2222";
}
console.log(i);
}
<table border="1" class="richtext-query-table"><tbody><tr><td>Column 0</td><td>Column 1</td><td>Column 2</td><td>Column 3</td><td>Column 4</td></tr><tr><td>Column 5</td><td>£3K</td><td>5,748</td><td>£0.45</td><td>0.93 %</td></tr><tr><td></td><td>--</td><td>4,551</td><td>£0.00</td><td>0.66 %</td></tr></tbody></table>
but I am getting an error because of the fact that the script applies for every td in the table. Now, I am trying to make it work only for the tds of the first row.
var columns = document.getElementsByTagName('tr:first-child > td');
for (var i=1; i<columns.length; i++)
{
if(document.querySelector('tr:nth-child(1) > td:nth-child('+i+')').innerHTML.includes("Column 1"))
{
document.querySelector('tr:nth-child(1) > td:nth-child('+i+')').innerHTML = "1111";
}
if(document.querySelector('tr:nth-child(1) > td:nth-child('+i+')').innerHTML.includes("Column 2"))
{
document.querySelector('tr:nth-child(1) > td:nth-child('+i+')').innerHTML = "2222";
}
console.log(i);
}
<table border="1" class="richtext-query-table"><tbody><tr><td>Column 0</td><td>Column 1</td><td>Column 2</td><td>Column 3</td><td>Column 4</td></tr><tr><td>Column 5</td><td>£3K</td><td>5,748</td><td>£0.45</td><td>0.93 %</td></tr><tr><td></td><td>--</td><td>4,551</td><td>£0.00</td><td>0.66 %</td></tr></tbody></table>
and it does not work unless I try using the eq function from this answer:
LINK
although I am having limitations with the functions in the platform I am using. I can use another line to get the first row and then get the columns from the first row (for statement) but I am guessing there is an easier way by just changing the part:
var columns = document.getElementsByTagName('tr:first-child td');
It looks simple but I cannot find a solution.
document.getElementsByTagName('tr')[0] it will return first tr, then row.querySelectorAll('td') get all columns of first row.
var row = document.getElementsByTagName('tr')[0];
var columns = row.querySelectorAll('td');
for (var i = 1; i < columns.length; i++) {
if (row.querySelector('tr:nth-child(1) > td:nth-child(' + i + ')').innerHTML.includes("Column 1")) {
row.querySelector('tr:nth-child(1) > td:nth-child(' + i + ')').innerHTML = "1111";
}
if (row.querySelector('tr:nth-child(1) > td:nth-child(' + i + ')').innerHTML.includes("Column 2")) {
row.querySelector('tr:nth-child(1) > td:nth-child(' + i + ')').innerHTML = "2222";
}
console.log(i);
}
<table border="1" class="richtext-query-table">
<tbody>
<tr>
<td>Column 0</td>
<td>Column 1</td>
<td>Column 2</td>
<td>Column 3</td>
<td>Column 4</td>
</tr>
<tr>
<td>Column 5</td>
<td>£3K</td>
<td>5,748</td>
<td>£0.45</td>
<td>0.93 %</td>
</tr>
<tr>
<td></td>
<td>--</td>
<td>4,551</td>
<td>£0.00</td>
<td>0.66 %</td>
</tr>
</tbody>
</table>