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>
Related
first I'm sorry if at some point I express myself badly, English is not my native language. I am developing an application in which the user sends 2 values through a form and in another page I use one of those data (string with comma separated options) to show a specific table and hide the others, and with the second data (Integer) I show one of the rows of that table.
What I already have:
I have the form and send the data through the Query String, I capture that data, I assign a variable to the integer and to the text string I separate it by commas and create an array.
URL Example: app.tables.example/?id=123&ops=option1%2c+option2
//Read parameters sent by form
const param = new Proxy(new URLSearchParams(window.location.search), {
get: (searchParams, prop) => searchParams.get(prop)
});
//Assign integer to a variable
let num = param.id;
//Assign options to a variable
let op = param.ops;
//Separate string with commas
let opsplit = op.split(',');
Up to here everything is perfect, I can print all the variables without any problem, now I need to compare the array with the id of each table, show the one that corresponds and hide the others. (The id of the tables is the same that user passes with the text string).
The tables look something like this:
<div id="option1" class="table-1">
<table width="100%">
<thead>
<tr>
<th align="left">Option1</th>
<th align="left">Integer</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left">Number</td>
<td align="left">Info</td>
</tr>
<tr>
<td align="left">1</td>
<td align="left">textblock</td>
</tr>
<tr>
<td align="left">2</td>
<td align="left">textblock</td>
</tr>
</tbody>
</table>
</div>
//As you can see the id of each table corresponds to what the user chose
<div id="option2" class="table-1">
<table width="100%">
<thead>
<tr>
<th align="left">Option2</th>
<th align="left">Integer</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left">Number</td>
<td align="left">Info</td>
</tr>
<tr>
<td align="left">1</td>
<td align="left">textblock</td>
</tr>
<tr>
<td align="left">2</td>
<td align="left">textblock</td>
</tr>
</tbody>
</table>
</div>
The problem:
I'm supposed to use the array elements in a "for" loop and compare them with the id of each table, then show that table and hide others, but I don't know exactly how to do it.
function myFunction() {
var input, filter, table, tr, td, i, y, txtValue;
for (r = 0; r<opsplit.length; r++){
input = opsplit[r];
filter = function(x){
return x.toUpperCase();
};
opsplit = opsplit.map(filter);
}
//When I test this, it does not return any value,
//innerHTML error
for(y = 0; y<opsplit.length; y++){
table = document.getElementById(opsplit[y]).innerHTML;
//I use this section to test, it should show me the row,
//but since the previous loop failed, it does nothing.
// What I really need is to show the whole
// table where this data is located and hide the other tables.
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
}
myFunction();
I am really stuck at the moment and would appreciate any help. What is the correct way to use the string array, and how can I hide the tables that the user does not need?
Ok, thanks to those who took the time to write a comment, but I found the solution, I had to convert the form data to a string and an integer. Then I was able to compare that string to the classes id. I am writing the answer in case anyone finds it useful.
//Read parameters sent by form
const param = new Proxy(new URLSearchParams(window.location.search), {
get: (searchParams, prop) => searchParams.get(prop)
});
//Assign number to a variable
let num = param.id;
//Convert to integer
let numint = parseInt(num);
//Assign options to a variable
let op = param.ops;
//Convert to String
let opstr = op.string();
//Separate string with commas
let opsplitstr = opstr.split(',');
//Assign class to a variable
tableclass = document.getElementsByClassName('table-1');
//Compare table class ids with string array
if (opsplitstr[0] == tableclass[0].id{
}
//We need a loop if we need compare all elements
TLDR: The URL does not send information about the data type, so I had to read it and convert it according to my need.
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>
I am getting a Table from a database like this (row numbers may vary):
|Player 1|Player 2|
-------------------
|Danny |Danny |
|John |John |
|Mary |Mary |
I want to select two names, one from each Player column, and store them in two variables, say player1_id and player2_id which I will later use to insert data into the database. I also want to highlight the names when they are clicked. The highlight and the associated variable value should change when I click on another name.
For example, let's say I click on Danny and John from Player 1 and Player 2 respectively. These two names should get highlighted and the variables should get player1_id = "Danny" and player2_id = "John". If I change my mind and click on Mary on the Player 2 column, Mary should get highlighted, John should lose its highlight and player2_id should change to "Mary"
So far I managed to sort of getting only the highlight part (but when I click more than one names all stay highlighted). Could anyone point me to a correct direction, please?
Here is the JSFiddle code of what I have so far
try this: https://jsfiddle.net/dunsondog109/behcgwLf/7/
function inputClickHandler(e){
e = e||window.event;
var all = document.getElementsByTagName("td");
var tdElm = e.target||e.srcElement;
var tdIndex = tdElm.cellIndex;
var numberOfColumns = 2;
if(tdElm.style.backgroundColor == 'rgb(46, 204, 64)'){
tdElm.style.backgroundColor = '';
} else {
for (var i=0;i<all.length;i++) {
if (i%numberOfColumns==tdIndex%numberOfColumns) {
// It is in the same column
all[i].style.backgroundColor = '';
}
}
tdElm.style.backgroundColor = '#2ECC40';
}
}
You need to reset all the tds in your column first and then set the td that was clicked
maybe it will not help you, but this is what I created for fun ...
As I'm jQuery user I find it difficult to list the table for any actions using plain javascript ... I would prefer having list of players in some object, draw the table based on that list. Instead of adding css to table cell i would add class like active and then just easily remove / move that class to different player. Maybe even adding some classes or other data-attributes to the table cells to help identify correct row / cell ... Anyway, everything is possible, but with this design you will not get far with your project I think. Good luck.
var Game = function() {
var players = {};
var table = document.querySelector('#myTable');
var rows = table.querySelectorAll('tr');
function uncheckPlayers(col) {
for ( var i=0; i<rows.length; i++ ) {
var tds = rows[i].querySelectorAll('td');
for ( var x=0; x<tds.length; x++ ) {
if ( col === x ) {
tds[x].style.backgroundColor = '';
}
}
}
}
for ( var i=0; i<rows.length; i++ ) {
var tds = rows[i].querySelectorAll('td');
for ( var x=0; x<tds.length; x++ ) {
tds[x].addEventListener('click', function() {
var id = x;
return function() {
uncheckPlayers(id);
players[id] = new Player(id, this.innerText);
this.style.backgroundColor = 'red';
console.log(players);
}
}(x));
}
}
}
var Player = function(id, name) {
this.name = name;
this.id = id;
this.score = 0;
console.log(this);
};
var Game = new Game();
<html>
<head>
<title>Find table cell value on cell (table) click using JavaScript</title>
</head>
<body>
<center>
Click on table below to select Players.
<br />
<br />
</center>
<table align="center" id="myTable" border="1" style="cursor: pointer;">
<tr>
<th>Player 1</th><th>Player 2</th>
</tr>
<tr>
<td>Danny</td><td>John</td>
</tr>
<tr>
<td>John</td><td>Danny</td>
</tr>
<tr>
<td>Mary</td><td>Mary</td>
</tr>
</table>
<br />
</body>
</html>
How to shuffle and store each character of the string inside the table such that 1st letter of the pair is in random row position and 2nd letter of the pair is in random column position so that the 2 characters do not conflict in same row or column?
this is my code for creating a 7x7 grid
<table border="5px" cellspacing="30" align="center" class="table-bordered" style="color:#FFFFFF" width="400px" height="200px">
<% for(int row=1; row <= 7; row++) { %>
<tr>
<% for(int col=1; col<=7; col++) { %>
<td></td>
<% } %>
</tr>
<% } %>
</table>
And this is my code for shuffling of a string
<script>
function f1() {
var str = "abcdefghijklmnopqrstuvwxyz1234567890!##$%^&*()<>?";
var shuffled = str.split('').sort(function({
return0.2Math.random();
}).join('');
document.write(shuffled);
}
</script>
Now I want this shuffled string to get split up and get stored into each cell of the table.
Why are you troubling your jsp to do this? Let your scripting (jQuery) do this. In your HTML add id attribute to your table like this,
<div id="myDiv">
<table id="myTable" border="5px" cellspacing="30"
align="center" class="table-bordered" width="400px" height="200px">
<!-- Your content goes here -->
</table>
</div>
And in your scripting use the shuffled string you can create table like this,
$(document).ready(function() {
var myWord = "hello"; //Use any shuffled string
var length = myWord.length;
var createTable = '<tr>';
for ( var i=0; i < length; i++) { //Iterate through each character
if (myWord.charAt(i) != " ") {
// Create as table cell
createTable = createTable+'<td>'+myWord.charAt(i)+'</td>';
}
};
createTable = createTable+'</tr>';
$("#myTable").append(createTable);
});
Check the working sample.
Update :
Hope this is you're asking, how to find specific table definition.
$('#mytable tr').each(function() {
$(this).find("td:eq(0)").html("Your Shuffled Character maybe h"); // First cell
});
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];