Copy text list to html table - javascript

I have a table on a form that is formatted like this:
<table id='leaderTable'>
<tbody>
<tr>
<td> Name1</td><td> item1</td><td> item2</td> <td> item3</td><td> item4</td><td> item5</td>
</tr>
<tr>
<td> Name2</td> <td> item1</td> <td> item2</td><td> item3</td><td> item4</td><td> item5</td>
</tr>
<tr>
<td> Name3</td>
-- etc. --
I search for and find a given Name in col-1 of this table, extract the data from cells to the right of that found Name, and copy them to a list in a textArea (id=leaderInfoArea).
Then I want to edit this text and copy it back to the original table, replacing the old data.
I've got the first part working and can extract the data to the textArea, but now I'm stuck and I don't know how to get it back to the table.
Here's how I'm extracting each record from the html table.
function getLeaderData() { // match the Pod Leader's entered name on the form (leaderName) against each cell in col-1 of leaderTable
let leaderInfoArea = document.getElementById('leaderInfoArea') ;
let leaderName = document.getElementById('leaderName').value.trim();
leaderName = leaderName.toLowerCase();
leaderName = leaderName.replace( '.' , ' ').replace(/ +/g, ' ');
let tab = document.getElementById('leaderTable');
let tabRows = tab.rows;
for (let i = 0; i < tabRows.length; i++) {
let leaderNameCell = tabRows[i].cells[0];
let nextLeaderName = leaderNameCell.innerText.trim();
nextLeaderName = nextLeaderName.toLowerCase();
nextLeaderName = nextLeaderName.replace.( '.' , ' ').replace(/ +/g, ' ');
if (leaderName === nextLeaderName) { // if the names match, copy the data for this Pod Leader into leaderInfoArea, and exit
leaderInfoArea.value = "";
for (let j = 0; j < tabRows[i].cells.length; j++) {
leaderInfoArea.value += tabRows[i].cells[j].innerText + "\r";
}
return;
}
}
}
leaderInfoArea now contains a list 6 lines high, although I can't get this editor to show that.
Name2
item1
item2
item3
item4
item5
Could someone please suggest how I can get this list back into the html table?

Related

How to find the last table cell which doesn't have text value and put a message?

I want to detect the last table row cell of a table which doesn't have any value (text).
var all_product_cell = document.getElementsByClassName("product-cell");
for (var i = 0; i < all_product_cell.length; i++) {
var td = all_product_cell[i];
alert(all_product_cell.length);
}
This code returns the table rows length... but I don't know how to check the last row which is clean and put there a message "hello!"...
UPDATE :
With this code system find last cell and put HELLO, but how I check the last cells who haven't text value and put the Hello there?
var all_local_cell = document.getElementsByClassName("product-cell");
for (var i = 0; i < all_local_cell.length; i++) {
var td = all_local_cell[i];
total_rows = all_local_cell.length-1;
all_product_cell[total_rows].value = "HELLO";
const productTable = document.querySelector(".your-product-table"); // get the table
const textOnLastCell = productTable
.rows[productTable.rows.lenght -1] // get last row
.cells[productTable.rows[productTable.rows.lenght -1].cells.lenght -1] // get last cell of last row
.innerText // get inner text
You can get last row of table by using below line :
var product_table = document.getElementsByClassName("product-cell");
console.log(product_table);
for (var i = 0; i < product_table.length; i++) {
total_rows = product_table[i].rows.length;
last_row = product_table[i].rows[total_rows-1];
last_row_length = last_row.cells.length;
last_column = last_row.cells[last_row_length-1]; // directly get last cell
If(last_column.innerHTML() == “”){
last_column.innerHTML = “Hello friend”;
}
console.log(last_column.innerHTML);
for(var j =0;j<last_row.cells.length;j++){ // you can find through loop using which cells is empty
console.log(last_row.cells[j]);
}
// console.log(last_row);
}
If you give html code will help better way.
https://codepen.io/aviboy2006/pen/ZEYBWWE
Here's a table with two empty TD'S.
The function will get an array of all TD's with the class product-cell and loop through each cell and check if innerHTML is empty, and then it will set lastTD to the last empty TD and set its innerHTML to "Hallo"
setTextLastEmptyCell()
function setTextLastEmptyCell(){
let tds = document.getElementsByClassName('product-cell')
for(let td of tds){
if(td.innerHTML === '') lastTD = td
}
lastTD.innerHTML = 'HALLO'
}
<table>
<tr>
<td class="product-cell">ABC</td>
<td class="product-cell">DEF</td>
<td class="product-cell">CBA</td>
</tr>
<tr>
<td class="product-cell"></td>
<td class="product-cell">CDA</td>
<td class="product-cell">ACB</td>
</tr>
<tr>
<td class="product-cell">ABC</td>
<td class="product-cell"></td>
<td class="product-cell">DEF</td>
</tr>
</table>

How to add and subtract numbers via JavaScript in an HTML table

I want to add numbers in <td></td> below via JavaScript. For example using the following description:
<td id='last'> + formatNumber(data.tickers[key].last) + </td>
<td id='high'> + formatNumber(data.tickers[key].high) + </td>
<td id='low'> + formatNumber(data.tickers[key].low) + </td>
How do I change the text of table data elements via JavaScript?
<td id='new1'> = + <td id='last'> + <td id='high'> + </td>
<td id='new2'> = + <td id='high'> + <td id='loww'> + </td>
Try this:
// these target the cell elements
let last = document.getElementById("last");
let high = document.getElementById("high");
let low = document.getElementById("low");
let new1 = document.getElementById("new1");
let new2 = document.getElementById("new2");
// now we convert cell content to numbers, add them and make them 2 decimal places.
new1.textContent = (parseFloat(last.textContent) + parseFloat(high.textContent)).toFixed(2);
new2.textContent = (parseFloat(high.textContent) + parseFloat(low.textContent)).toFixed(2);
td {
border: solid 1px;
}
<table>
<tr>
<th>last</th>
<th>high</th>
<th>low</th>
<th>new1</th>
<th>new2</th>
</tr>
<tr>
<td id='last'> 23.40 </td>
<td id='high'> 28.20 </td>
<td id='low'> 22.10 </td>
<td id='new1'></td>
<td id='new2'></td>
</tr>
</table>
First I'm going to make your life a bit easier. Instead of using document.getElementsByTagName('tr')[3].getElementsByTagName('td')[2] to get the fourth tr element's third td element ([0] = first, [2] = third, etc) this will help make your code much much easier to read. You don't need id attributes on every element if you know how reliable code and order are by default.
function tag_(t)
{//Example: tag_('body')[0];
return (document.getElementsByTagName(t)) ? document.getElementsByTagName(t) : false;
}
Object.prototype.tag_ = function(t)
{//Example: id_('unique_id').tag_('td')[0];
return (this.getElementsByTagName && this.getElementsByTagName(t) && this.getElementsByTagName(t).length > 0) ? this.getElementsByTagName(t) : false;
}
Secondly the easiest way to both read and write data to any element is to use textContent.
Read the fourth td on the third tr:
//Read an element's text node:
console.log(tag_('tr')[2].tag_('td')[5].textContent);
//Write to an element's text node:
tag_('table')[0].tag_('tr')[2].tag_('td')[5].textContent = '1,234');
JavaScript is a bit strict when it comes to types. So if you need to do some math with text content that you just read you need to convert it:
Number(tag_('tr')[1].tag_('td')[5].textContent);//'123' becomes `123`
Number(tag_('tr')[2].tag_('td')[2].textContent);//'a123' becomes `NaN` (Not a Number)
If I recall correctly I recently used the following to strip non-numeric text from a string:
var my_number = Number('String or replace with object reference'.replace(/\D/g,''));
Now that you're getting the read/write aspects and overcoming some of the more oddities associated with it I'll iterate over...iteration! You may already know this though I'm presuming a full answer is more desirable than a partial answer for not just you though also others reading this in the future.
var table = tag_('table');
for (var i = 0; i < table.length; i++)
{
console.log(table[i]);
var tr = table[i].tag_('tr');//Whatever table[i] is and it's table rows.
for (var j = 0; j < tr[i].length; j++)
{
console.log(tr[j]);
var td = table[i].tag_('tr')[j].tag_('td');//All the table data elements.
for (var k = 0; k < td.length; k++)
{
//apply read/write conditions here.
//potentially call a second global function to keep your code reusable.
}
}
}
That should help you get far enough with specific and iteral targeting of table data elements to help you learn and achieve your goals.

How to populate data cells in Javascript vertically?

I have this (name, value) table in HTML and I want to populate the 'value' column after some computations.
The 'name' column is filled up at the time of loading of the webpage, while the 'value' column remains blank at that time.
After performing some computations, I'd like to populate the 'value' column for each row corresponding to the 'name', serially. From 1 -> n.
What my page does:
Get a number from the user (say 3).
Get 3 names.
Print out a table of 3 rows of pairs, leaving the 'value' column blank.
Perform some computation and store them in an array called 'value'.
What next:
I want to populate the 'value' column for every element stored in the 'value' array, serially i.e. from 1 -> n.
Here's some code:
JavaScript - Dynamic creation of the table according to the number received at the beginning
var playerTable = document.getElementById("player_table");
var player_table_row, player_table_datacell1, player_table_datacell2;
var value;
//no_of_players contains the number of rows
for ( var i = 0; i < no_of_players; i++)
{
//inserts i'th row
player_table_row = playerTable.insertRow(i);
//Insert first datacell for the row
player_table_datacell1 = player_table_row.insertCell( 0 );
//Insert second datacell for the row
player_table_datacell2 = player_table_row.insertCell( 1 );
//Inserts the name for the i'th row in the 'name' column
//players_list is the array containing all the names
player_table_datacell1.innerHTML = players_list[i];
//Leave the second cell i.e. 'value' column blank
player_table_datacell2.innerHTML = "";
value[i] = /* Some computations */
}
HTML code for the table, it's a simple one
<table id = "player_table">
<th>Name</th>
<th>Value</th>
</table>
Expected output:
Name Value
A 5
B 2
C 19
I have calculated those values 5, 2, 19 in advance and now just need to populate them in the HTML table. My current table looks like this:
Name Value
A
B
C
I assume your computations require some kind of user input. And that is the reason why, you couldn't do the computation and then add rows to the table with Name and computed values.
Here is one way of doing it. I am just setting the id for each value cell and use the id to update. Hope it helps :)
<body>
<table id = "player_table">
<thead>
<th>Name</th>
<th>Value</th>
</thead>
</table>
<script type="text/javascript">
process();
function process() {
var playerTable = document.getElementById("player_table");
var player_table_row, player_table_datacell1, player_table_datacell2;
var value;
//hard coding for testing purposes
no_of_players = 3;
var players_list = ["A", "B", "C"];
//no_of_players contains the number of rows
for (var i = 0; i < no_of_players; i++) {
//inserts i'th row
player_table_row = playerTable.insertRow(i + 1);
//Insert first datacell for the row
player_table_datacell1 = player_table_row.insertCell(0);
//Insert second datacell for the row
player_table_datacell2 = player_table_row.insertCell(1);
player_table_datacell2.id = "value_cell_" + String(i);
//Inserts the name for the i'th row in the 'name' column
//players_list is the array containing all the names
player_table_datacell1.innerHTML = players_list[i];
//Leave the second cell i.e. 'value' column blank
player_table_datacell2.innerHTML = "";
//value[i] = /* Some computations */
}
value = ["100", "200", "300"]; //hard coding for testing purposes
updateValueColumn(value);
}
function updateValueColumn(value) {
var value_cell;
for (var i = 0; i < value.length; i++) {
value_cell = document.getElementById("value_cell_" + String(i));
value_cell.innerHTML = value[i];
}
}
</script>
</body>
With a generated table like this:
<table id = "player_table">
<tr>
<th>Name</th>
<th>Value</th>
</tr>
<tr>
<td>A</td>
<td></td>
</tr>
<tr>
<td>B</td>
<td></td>
</tr>
<tr>
<td>C</td>
<td></td>
</tr>
</table>
You could use this code to get the second column as an array:
var valueCells = document.querySelectorAll("#player_table tr td:nth-child(2)");
Then just set the innerHTML on each cell in some loop.
valueCells[i].innerHTML = value[i];

I need the id and name of inner element when cloning a row of a table with javascript

When hitting areasensornewline_button, a new row gets created and appended to the table. I can change the row ID, but all new dropdownboxes within this row now have id="selectedArea0", id="selectedSensor0" and name="AreaBinding0", name="sensorBinding0". These have to be 1, 2 and so fort. Any help would much be appreciated!!!!
<table border="0" id="areasensor_table">
<tr id="areasensor_row0">
<td id="area_column0">
<select name="areaBinding0" id="selectedArea0"> #for(area <- areas) {
<option value="#area.uniqueid">#area.name</option>}
</select>
</td>
<td id="sensor_column0">
<select name="sensorBinding0" id="selectedSensor0"> #for(sensor <- sensors) {
<option value="#sensor.id">#sensor.name</option> }
</select>
</td>
<td>
<a class="glyphicon glyphicon-plus" id="areasensornewline_button"></a>
</td>
</tr>
</table>
<p>
<p>
<script>
var q = 1;
document.getElementById('areasensornewline_button').onclick = cloneRowAreaSensor;
function cloneRowAreaSensor() {
var row = document.getElementById('areasensor_row0'); // find row to copy
var table = document.getElementById('areasensor_table'); // find table to append to
var clone = row.cloneNode(true); // copy children too
var innerClone = row.innerHTML;
clone.id = 'areasensor_row' + q; // change id or other attributes/contents
q++;
table.appendChild(clone); // add new row to end of table
}
</script>
A trick is to use Regular expression but is far to be perfect ...
function cloneRowAreaSensor() {
var row = document.getElementById('areasensor_row0'); // find row to copy
var table = document.getElementById('areasensor_table'); // find table to append to
var clone = row.cloneNode(true); // copy children too
clone.innerHTML = clone.innerHTML.replace(/0"/g, q + '"');
clone.id = 'areasensor_row' + q; // change id or other attributes/contents
q++;
table.appendChild(clone); // add new row to end of table
}
The added row is placed outside the tbody html tag. You really should use jQuery, il will help you a lot.
Your code only works first time. Create a counter use it to name element.
Example:
var count = 1;
for(i = 0; i<= 10; i++){
var row = document.getElementById('areasensor_row'+ count +'');
}
It is a simple example. You need to restructure your code like this example. (This cicle for isnt better example, but it works at 10 elements)

Get a particular cell value from HTML table using JavaScript

I want to get each cell value from an HTML table using JavaScript when pressing submit button.
How to get HTML table cell values?
To get the text from this cell-
<table>
<tr id="somerow">
<td>some text</td>
</tr>
</table>
You can use this -
var Row = document.getElementById("somerow");
var Cells = Row.getElementsByTagName("td");
alert(Cells[0].innerText);
function Vcount() {
var modify = document.getElementById("C_name1").value;
var oTable = document.getElementById('dataTable');
var i;
var rowLength = oTable.rows.length;
for (i = 1; i < rowLength; i++) {
var oCells = oTable.rows.item(i).cells;
if (modify == oCells[0].firstChild.data) {
document.getElementById("Error").innerHTML = " * duplicate value";
return false;
break;
}
}
var table = document.getElementById("someTableID");
var totalRows = document.getElementById("someTableID").rows.length;
var totalCol = 3; // enter the number of columns in the table minus 1 (first column is 0 not 1)
//To display all values
for (var x = 0; x <= totalRows; x++)
{
for (var y = 0; y <= totalCol; y++)
{
alert(table.rows[x].cells[y].innerHTML;
}
}
//To display a single cell value enter in the row number and column number under rows and cells below:
var firstCell = table.rows[0].cells[0].innerHTML;
alert(firstCell);
//Note: if you use <th> this will be row 0, so your data will start at row 1 col 0
You can also use the DOM way to obtain the cell value:
Cells[0].firstChild.data
Read more on that in my post at http://js-code.blogspot.com/2009/03/how-to-change-html-table-cell-value.html
You can get cell value with JS even when click on the cell:
.......................
<head>
<title>Search students by courses/professors</title>
<script type="text/javascript">
function ChangeColor(tableRow, highLight)
{
if (highLight){
tableRow.style.backgroundColor = '00CCCC';
}
else{
tableRow.style.backgroundColor = 'white';
}
}
function DoNav(theUrl)
{
document.location.href = theUrl;
}
</script>
</head>
<body>
<table id = "c" width="180" border="1" cellpadding="0" cellspacing="0">
<% for (Course cs : courses){ %>
<tr onmouseover="ChangeColor(this, true);"
onmouseout="ChangeColor(this, false);"
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');">
<td name = "title" align = "center"><%= cs.getTitle() %></td>
</tr>
<%}%>
........................
</body>
I wrote the HTML table in JSP.
Course is is a type. For example Course cs, cs= object of type Course which had 2 attributes: id, title.
courses is an ArrayList of Course objects.
The HTML table displays all the courses titles in each cell. So the table has 1 column only:
Course1
Course2
Course3
......
Taking aside:
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');"
This means that after user selects a table cell, for example "Course2", the title of the course- "Course2" will travel to the page where the URL is directing the user: http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp . "Course2" will arrive in FoundS.jsp page. The identifier of "Course2" is courseId. To declare the variable courseId, in which CourseX will be kept, you put a "?" after the URL and next to it the identifier.
I told you just in case you'll want to use it because I searched a lot for it and I found questions like mine. But now I found out from teacher so I post where people asked.
The example is working.I've seen.
Just simply.. #sometime when larger table we can't add the id to each tr
<table>
<tr>
<td>some text</td>
<td>something</td>
</tr>
<tr>
<td>Hello</td>
<td>Hel</td>
</tr>
</table>
<script>
var cell = document.getElementsByTagName("td");
var i = 0;
while(cell[i] != undefined){
alert(cell[i].innerHTML); //do some alert for test
i++;
}//end while
</script>
<td class="virtualTd" onclick="putThis(this)">my td value </td>
function putThis(control) {
alert(control.innerText);
}
I found this as an easiest way to add row . The awesome thing about this is that it doesn't change the already present table contents even if it contains input elements .
row = `<tr><td><input type="text"></td></tr>`
$("#table_body tr:last").after(row) ;
Here #table_body is the id of the table body tag .
Here is perhaps the simplest way to obtain the value of a single cell.
document.querySelector("#table").children[0].children[r].children[c].innerText
where r is the row index and c is the column index
Therefore, to obtain all cell data and put it in a multi-dimensional array:
var tableData = [];
Array.from(document.querySelector("#table").children[0].children).forEach(function(tr){tableData.push(Array.from(tr.children).map(cell => cell.innerText))});
var cell = tableData[1][2];//2nd row, 3rd column
To access a specific cell's data in this multi-dimensional array, use the standard syntax: array[rowIndex][columnIndex].
Make a javascript function
function addSampleTextInInputBox(message) {
//set value in input box
document.getElementById('textInput').value = message + "";
//or show an alert
//window.alert(message);
}
Then simply call in your table row button click
<td class="center">
<a class="btn btn-success" onclick="addSampleTextInInputBox('<?php echo $row->message; ?>')" title="Add" data-toggle="tooltip" title="Add">
<span class="fa fa-plus"></span>
</a>
</td>

Categories

Resources