Change inner txt of table - javascript

I have a table with names, surnames and etc. I should change the value of the clicked td using input. I managed to changed the value of the first td but I am not sure how can change the values of specific td.
Here is my code.
let inp
let changevalue
let click = addEventListener("focus" ,function(){
changevalue = document.querySelector("td")
inp = document.createElement("input")
inp.value = changevalue.innerHTML
changevalue.innerHTML = " "
changevalue.append(inp)
})
let newclick = addEventListener("blur" , function(){
changevalue.innerHTML = inp.value
})
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<table style="width:100%" id = "TB">
<tr >
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr >
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
</body>
</html>

You can add click event listeners on each td element and use the blur event only for the dynamically created input.
const tds = document.querySelectorAll("#TB td");
tds.forEach(td => {
td.addEventListener("click", e=>{
let inp = document.createElement("input")
inp.value = td.innerHTML
td.innerHTML = " "
td.append(inp);
inp.focus();
inp.addEventListener("blur", e=>{
td.innerHTML = inp.value;
});
});
});
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<table style="width:100%" id = "TB">
<tr >
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr >
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
</body>
</html>

Related

Javascript Access to Only Header, Body or Footer Rows One at a Time

I have a need to traverse (using javascript) the sections of each table's rows individually. Meaning that I need to traverse the THEAD rows first, then the TBODY rows, and finally the TFOOT rows.
What I need to do requires far more complexity than just coloring the boxes, but for the purpose of this example i'm just trying to color the thead rows red, the tbody rows green and the tfoot rows yellow. If I can get these loops working for the rows for each section I can then take over from there to do the rest of the coding.
I've tried the below but it does not work (it tells me "rows is not defined"). Could someone fix the ColorBoxes() function code to get this to work? Just please do not give me CSS answers here because that does not solve the problem - I need to traverse through the rows of each section. Thanks!
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
<script language='javascript'>
function ColorBoxes()
{
var tbl = document.getElementById('MyTable');
for (var nRow = 0; nRow < tbl.tHead[0].rows; nRow++)
{
tbl.tHead[0].row[nRow].style.backgroundColor = 'red';
}
for (var nRow = 0; nRow < tbl.tBody[0].rows; nRow++)
{
tbl.tBody[0].row[nRow].style.backgroundColor = 'green';
}
for (var nRow = 0; nRow < tbl.tFoot[0].rows; nRow++)
{
tbl.tFoot[0].row[nRow].style.backgroundColor = 'yellow';
}
}
</script>
</head>
<body onLoad='ColorBoxes()'>
<h1>The thead, tbody, and tfoot elements</h1>
<table id='MyTable'>
<thead>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<th>Name</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Sum</td>
<td>$180</td>
</tr>
</tfoot>
</table>
</body>
</html>
You could do something like this. Using explicit selectors might help you reason with your loops a little better.
function ColorBoxes() {
const table = document.querySelector('#MyTable')
const thead_tr = table.querySelectorAll('thead tr')
const tbody_tr = table.querySelectorAll('tbody tr')
const tfoot_tr = table.querySelectorAll('tfoot tr')
thead_tr.forEach(row => {
row.style.backgroundColor = 'red'
})
tbody_tr.forEach(row => {
row.style.backgroundColor = 'green'
})
tfoot_tr.forEach(row => {
row.style.backgroundColor = 'yellow'
})
}
ColorBoxes()
<!DOCTYPE html>
<html>
<head>
<style>
table,
th,
td {
border: 1px solid black;
}
</style>
</head>
<body>
<h1>The thead, tbody, and tfoot elements</h1>
<table id='MyTable'>
<thead>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<th>Name</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Sum</td>
<td>$180</td>
</tr>
</tfoot>
</table>
</body>
</html>

Adding a new row to table using Javascript

When the user clicks the add new button a new row should be added to the bottom of the table, but when I click the button, nothing happens. The script looks fine to me and I've tried to find a solution for hours.
function addRow(tableID) {
var table = document.getElementById(tableID),
row = tbl.insertRow(tbl.rows.length),
i;
for (i = 0; i < table.rows[0].cells.length; i++) {
createCell(row.insertCell(i), i, 'row');
}
}
<head>
<style>
table, th, td{
border: 1px solid black;
}
</style>
</head>
<body>
<table id="countries">
<thead>
<tr>
<th>Country</td>
<th>Code</td>
</tr>
</thead>
<tbody>
<tr>
<td>Algeria</td>
<td>213</td>
</tr>
</tbody>
</table>
<button type="button" onclick="addRow('countries');">Add New</button>
</body>
You can try this :
function addRow(tableID) {
var table = document.getElementById(tableID),
row = table.insertRow(table.rows.length),
i;
for (i = 0; i < table.rows[0].cells.length; i++) {
createCell(row.insertCell(i), i, 'row');
}
}
function createCell(cell, text, style) {
var div = document.createElement('div'),
txt = document.createTextNode(text);
div.appendChild(txt);
div.setAttribute('class', style);
div.setAttribute('className', style);
cell.appendChild(div);
}
<html>
<title>Test</title>
<head>
<style>
table, th, td{
border: 1px solid black;
}
</style>
</head>
<body>
<table id="countries">
<thead>
<tr>
<th>Country</td>
<th>Code</td>
</tr>
</thead>
<tbody>
<tr>
<td>Algeria</td>
<td>213</td>
</tr>
</tbody>
</table>
<button type="button" onclick="addRow('countries');">Add New</button>
</body>
</html>
You can done this with very little code using JQuery. check below code here :-
$(document).ready(function(){
$(".add").click(function(){
$("#countries tbody tr:last-child").after("<tr><td>Data</td><td>data</td></tr>")
});
});
table, th, td{
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="countries">
<thead>
<tr>
<th>Country</th>
<th>Code</th>
</tr>
</thead>
<tbody>
<tr>
<td>Algeria</td>
<td>213</td>
</tr>
</tbody>
</table>
<button class="add" type="button">Add New</button>
I hope that this is what you are looking for,
<script>
function addRow(tableID) {
var table = document.getElementById(tableID); // get tableById
var rowCount = table.rows.length; // get row count
var cellCount = table.rows[0].cells.length; // get cell count
var row = table.insertRow(rowCount); // create row
for(var i =0; i <= cellCount; i++){
createCell(row.insertCell(i), i, 'row');
}
}
</script>

Adding HTML table rows and columns using Javascript Array , not working

I am working with HTML table and JS array. I have table header and last row of Subtotal.
I have tried to create and add rows with the code below but it's not working. The code should read the array elements and should create rows as per the number of elements and then add columns to it as well.
Help me please!
var titles = ["Book 1","Book 2","Book 3"];
var quantities = [3,1,2];
var prices = [80,125,75];
var GrandTotal = 0;
function myTable() {
for(var i=0;i<titles.length;i++){
var x = document.createElement("TR");
x.setAttribute("id", "myTr[i]");
document.getElementById("table").appendChild(x);
for(var j=0;titles.length;j++){
//creating Title columns
var titleColumn = document.createElement("TD");
var titleColumnText = document.createTextNode(titles[j]);
//adding title values
titleColumn.appendChild(titleColumnText);
document.getElementById("myTr[i]").appendChild(titleColumn);
//creating Quantity columns
var qtyColumn = document.createElement("TD");
var qtyColumnText = document.createTextNode(quantities[j]);
//adding Quantity values
qtyColumn.appendChild(qtyColumnText);
document.getElementById("myTr[i]").appendChild(qtyColumn);
//creating Price columns
var priceColumn = document.createElement("TD");
var priceColumnText = document.createTextNode(prices[j]);
//adding Price values
priceColumn.appendChild(priceColumnText);
document.getElementById("myTr[i]").appendChild(priceColumn);
// Amount calculation
var amt=prices[j]*quantities[j];
//creating Amt columns
var amtColumn = document.createElement("TD");
var amtColumnText = document.createTextNode(amt);
//adding Amt values
priceColumn.appendChild(amtColumnText);
document.getElementById("myTr[i]").appendChild(amtColumn);
GrandTotal += amt;
}
}
}
document.getElementById("grandTotal").innerHTML= GrandTotal;
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Table and Array</title>
<style>
table{
border: 1px solid black;
border-collapse: collapse;
}
th, tr, td{
border: 1px solid black;
}
</style>
</head>
<body ">
<div class="title">
<h1>My Store</h1>
</div>
<table class="table-fill" id="table">
<thead>
<tr>
<th colspan="2">Product Title</th>
<th>Quantity</th>
<th>Price</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="5">I want to add rows anc columns here dynamically</td>
</tr>
<tr class="totals">
<td colspan="4" id="subTotal">Subtotal</td>
<td id="grandTotal"></td>
</tr>
</tbody>
</table>
<script src="js/data.js" type="text/JavaScript"></script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Table and Array</title>
<style>
table{
border: 1px solid black;
border-collapse: collapse;
}
th, tr, td{
border: 1px solid black;
}
</style>
</head>
<body ">
<div class="title">
<h1>My Store</h1>
</div>
<table class="table-fill" id="table">
<thead>
<tr>
<th colspan="2">Product Title</th>
<th>Quantity</th>
<th>Price</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="5">I want to add rows anc columns here dynamically</td>
</tr>
<tr class="totals">
<td colspan="4" id="subTotal">Subtotal</td>
<td id="grandTotal"></td>
</tr>
</tbody>
</table>
</body>
<script>
var titles = ["Book 1","Book 2","Book 3"];
var quantities = [3,1,2];
var prices = [80,125,75];
var GrandTotal = 0;
function myTable() {
console.log('a')
for(var i=0;i<titles.length;i++){
var x = document.createElement("TR");
x.setAttribute("id", `${titles[i]}`);
document.getElementById("table").appendChild(x);
console.log(document.getElementById("table"))
//creating Title columns
var titleColumn = document.createElement("TD");
var titleColumnText = document.createTextNode(titles[i]);
//adding title values
titleColumn.appendChild(titleColumnText);
console.log(document.getElementById(`${titles[i]}, ${titles[i]}`))
document.getElementById(`${titles[i]}`).appendChild(titleColumn);
//creating Quantity columns
var qtyColumn = document.createElement("TD");
var qtyColumnText = document.createTextNode(quantities[i]);
//adding Quantity values
qtyColumn.appendChild(qtyColumnText);
document.getElementById(`${titles[i]}`).appendChild(qtyColumn);
//creating Price columns
var priceColumn = document.createElement("TD");
var priceColumnText = document.createTextNode(prices[i]);
//adding Price values
priceColumn.appendChild(priceColumnText);
document.getElementById(`${titles[i]}`).appendChild(priceColumn);
// Amount calculation
var amt=prices[i]*quantities[i];
//creating Amt columns
var amtColumn = document.createElement("TD");
var amtColumnText = document.createTextNode(amt);
//adding Amt values
amtColumn.appendChild(amtColumnText);
document.getElementById(`${titles[i]}`).appendChild(amtColumn);
GrandTotal += amt;
}
}
myTable();
var grandTotalText = document.createTextNode(GrandTotal);
document.getElementById("grandTotal").appendChild(grandTotalText)
</script>
</html>

Is there a way of obtaining the value of the TH when hoovering over a TD in a table on HTML? [duplicate]

This question already has answers here:
How can I get the corresponding table header (th) from a table cell (td)?
(6 answers)
Closed 4 years ago.
I am trying to obtain the value of a TH after hoovering over its TD. I am able to obtain the value of the TD data cell when I hoover over it but cannot find a way to get the value for the TH.
This javascript allows me to click on the TD to obtain the entire row of values or hoover over a particular cell to get the value of it. However, I can't seem to find a way to get the TH.
$('#grid').click(function(evt) {
var row = $(evt.target).parent('tr'); // Get the parent row
var cell = $(evt.target); //Get the cell
alert('Row data: ' + row.text());
alert('Cell data: ' + cell.text());
});
$('#grid').on('mouseenter', 'td', function() {
console.log($(this).text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<div id="grid">
<table id="table1" border="1">
<thead>
<th>ID</th>
<th>Name</th>
</thead>
<tbody>
<tr>
<td>101</td>
<td>Jackie</td>
</tr>
<tr>
<td>102</td>
<td>Thomas</td>
</tr>
</tbody>
</table>
Rather than using javascript or jquery to traverse the DOM to find the th involved- you could use a HTML5 data-attribute and set the vvalue for each td - then show that on the click (here i am consoling it for the snippet).
$('#table td').on('click', function() {
let col = $(this).attr('data-col');
let content = $(this).text();
console.log(col + ": " + content);
});
table {
border-collapse: collapse;
}
th {
border: solid 1px #d4d4d4;
border-bottom-width: 2px;
padding: 5px 10px
}
td {
border: solid 1px #d4d4d4;
padding: 5px 10px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table">
<thead>
<th>ID</th>
<th>Name</th>
</thead>
<tbody>
<tr>
<td data-col="ID">101</td>
<td data-col="Name">Jackie</td>
</tr>
<tr>
<td data-col="ID">102</td>
<td data-col="Name">Thomas</td>
</tr>
</tbody>
</table>
Alternatively - you could have an array of the th contents (espescially if you create the table dynamically) - then on the click of the td - get its index in its tr (again you could store this in a data-attribute - or as an id - then use that index to reference the array.
This ouwl be the better method use an array or object to create the table dynamically and then you already have the data source to reference the content from.
var columns = ['ID','Name'];
$('#table td').on('click', function() {
let index = parseInt($(this).attr('data-index'));
let col = columns[index];
let content = $(this).text();
console.log(col + ": " + content);
});
table {
border-collapse: collapse;
}
th {
border: solid 1px #d4d4d4;
border-bottom-width: 2px;
padding: 5px 10px
}
td {
border: solid 1px #d4d4d4;
padding: 5px 10px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table">
<thead>
<th>ID</th>
<th>Name</th>
</thead>
<tbody>
<tr>
<td data-index='0'>101</td>
<td data-index='1'>Jackie</td>
</tr>
<tr>
<td data-index='0'>102</td>
<td data-index='1'>Thomas</td>
</tr>
</tbody>
</table>
Based on thread linked in the comments, Ive created below code.
This console logs the text value of the TH and the value of the TD on mouseover.
$('#grid').click(function(evt) {
var row = $(evt.target).parent('tr'); // Get the parent row
var cell = $(evt.target); //Get the cell
alert('Row data: ' + row.text());
alert('Cell data: ' + cell.text());
});
$('#grid').on('mouseenter', 'td', function() {
var $td = $(this),
$th = $td.closest('table').find('th').eq($td.index());
console.log($th.text() + ": " + $td.text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="grid">
<table id="table1" border="1">
<thead>
<th>ID</th>
<th>Name</th>
</thead>
<tbody>
<tr>
<td>101</td>
<td>Jackie</td>
</tr>
<tr>
<td>102</td>
<td>Thomas</td>
</tr>
</tbody>
</table>
</div>
Find child-index-number of the td element under the tr element.
Find the th element by index.
//Find table
var table = document.getElementById('table');
//Hover event callback
function hoverTDEvent(evt) {
//Only run on td
if (evt.target.nodeName.toLowerCase() != 'td') {
return false;
}
//Find relative index
var index = Array.prototype.slice.call(evt.target.parentNode.children).indexOf(evt.target);
//Find th by index and log contents
console.log(table.querySelectorAll("th")[index].textContent,evt.target.textContent);
}
//Bind event
table.addEventListener("mousemove", hoverTDEvent);
<table id="table" border="1">
<thead>
<th>ID</th>
<th>Name</th>
</thead>
<tbody>
<tr>
<td>101</td>
<td>Jackie</td>
</tr>
<tr>
<td>102</td>
<td>Thomas</td>
</tr>
</tbody>
</table>
Notice that this wont work if you use the colspan property.

How to get value of nextsibling if element search by specific string?

I am trying to get the text which is in the next element of searched element by string.Let me explain by code
<table id="myTable">
<tbody>
<tr>
<th>Name</th>
<td>foo</td>
</tr>
<tr>
<th>age</th>
<td>20</td>
</tr>
</tbody>
</table>
I have to search string if "age" exist. then return 20 as its value.
I tried to search string by contains: But unable to access value
You could use jQuery next() and contains selector to achieve what you need.
$(document).ready(function() {
console.log($("th:contains(age)").next().html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
<tbody>
<tr>
<th>Name</th>
<td>foo</td>
</tr>
<tr>
<th>age</th>
<td>20</td>
</tr>
</tbody>
</table>
This solution will go through all the elements that are children of trs and check to see that their text is equal to the search. If it is equal, it assigns the next element to nextElem.
let search = "age";
let nextElem;
$('#myTable tr').children().each(function() {
if ($(this).text() === search)
nextElem = $(this).next();
});
console.log(nextElem.text())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
<tbody>
<tr>
<th>Name</th>
<td>foo</td>
</tr>
<tr>
<th>age</th>
<td>20</td>
</tr>
</tbody>
</table>
You've already set up the table to display name-value pairs, where each name is contained within <th>...</th> and its corresponding value is contained within <td>...</td>.
So one approach to this is straightforward Document Object Model navigation, using:
getElementsByTagName('th')
getElementsByTagName('td')
var table = document.getElementsByTagName('table')[0];
var button = document.getElementsByTagName('button')[0];
var summary = document.getElementsByClassName('summary')[0];
var searchedFor = summary.getElementsByTagName('p')[0];
var correspondingResult = summary.getElementsByTagName('p')[1];
function displayResult() {
var returnValue = '';
var searchString = document.getElementsByTagName('input')[0].value;
var lowerCaseSearchString = searchString.toLowerCase();
var tableRows = document.getElementsByTagName('tr');
for (var i = 0; i < tableRows.length; i++) {
var name = tableRows[i].getElementsByTagName('th')[0].textContent.toLowerCase();
if (name === lowerCaseSearchString) {
returnValue = tableRows[i].getElementsByTagName('td')[0].textContent;
}
if (returnValue === '') {
returnValue = 'No Matches';
}
}
searchedFor.textContent = 'You searched for... ' + '"' + searchString + '"';
correspondingResult.textContent = 'The corresponding result is... ' + '"' + returnValue + '"';
}
button.addEventListener('click',displayResult,false);
table, .search-panel {
display: inline-block;
vertical-align: top;
margin-right: 24px;
}
table {
border: 2px solid rgb(127,127,127);
}
th, td {
padding: 12px;
}
th {
text-align: left;
background-color: rgb(191,191,191);
}
th::after {
content:':';
}
.search-results p span {
font-weight:bold;
}
<table>
<tbody>
<tr>
<th>Name</th>
<td>Foo</td>
</tr>
<tr>
<th>Age</th>
<td>20</td>
</tr>
</tbody>
</table>
<div class="search-panel">
<form>
<input type="text" placeholder="Enter your string here..." value="" />
<button type="button">Search for String</button>
</form>
<div class="summary">
<p>You searched for... </p>
<p>The corresponding result is... </p>
</div>
</div>

Categories

Resources