Show calculated arithmetic mean in <td> when the button is clicked - javascript

please help me finish this, I'm getting nowhere.
what needs to be done
final results
I've explained in the pictures whats the finish goal.
This is a grade calculator.
There are 3 types of grades.. it should calculate the arithmetic mean for every category and arithmetic mean for all grades no matter which category they are.
Calculated values should be shown on the appropriate block, as shown in the picture.
input[type="number"]{
color : transparent;
text-shadow : 0 0 0 #000;
}
input[type="number"]:focus{
outline : none;
}
</style>
<body>
<div id="stranica" style="display: inline-block; position: left;">
<button type="button" onclick="javascript:dodajocenu();"> Add grade</button>
</div>
<div id="desna" style="display: inline-block; position: absolute; text-align: center;">
<button type="button" onclick=""> Calculate </button>
<br><br>
<table border="1">
<tbody>
<tr>
<td style="width:70px; text-align: center;">Written test</td>
<td style="width:70px; text-align: center;">Essay</td>
<td style="width:70px; text-align: center;">Class Activity</td>
</tr>
<tr>
<td style="text-align: center;"> </td> <!-- insert arithmetic mean of all Writtentest, inside td-->
<td style="text-align: center;"></td> <!-- insert arithmetic mean of all Essay, inside td-->
<td style="text-align: center;"></td> <!-- insert arithmetic mean of all ClassActivity, inside td-->
</tr>
</tbody>
</table>
<br>
<table border="1">
<tbody>
<tr>
<td style="width:140px; text-align: center;">Arithmetic mean of all grades</td>
</tr>
<tr>
<td style="text-align: center;"> </td> <!-- insert arithmetic mean of all numbers-->
</tr>
</tbody>
</table>
</div>
</body>
<script>
var ocena = 0;
var stranica = document.querySelector("#stranica")
function removeElement(obrisi) {
var dugme = obrisi.target;
stranica.removeChild(dugme.parentElement)
}
function dodajocenu() {
ocena++;
//create textbox
var input = document.createElement('input');
input.type = "number";
input.setAttribute("max",5);
input.setAttribute("min",1);
var myParent = document.body;
//Create array of options to be added
var array = ["Written test","Essay","Class Activity"];
//Create and append select list
var selectList = document.createElement('select');
selectList.id = "mySelect";
myParent.appendChild(selectList);
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement('option');
option.value = array[i];
option.text = array[i];
selectList.appendChild(option);
}
//create remove button
var remove = document.createElement('button');
remove.onclick = function(obrisiocenu) {
removeElement(obrisiocenu);
}
remove.setAttribute("type", "dugme");
remove.innerHTML = "-"; //delete
var item = document.createElement('div')
item.classList.add("item")
item.appendChild(input);
item.appendChild(selectList);
item.appendChild(remove);
stranica.appendChild(item)
}
</script>```

var ocena = 0;
function removeElement(obrisi) {
var dugme = obrisi.target;
document.getElementById("stranica").removeChild(dugme.parentElement)
}
function dodajocenu() {
ocena++;
//create textbox
var input = document.createElement('input');
input.type = "number";
input.setAttribute("max", 5);
input.setAttribute("min", 1);
var myParent = document.body;
//Create array of options to be added
var array = ["Kontrolni", "Vezbe", "Aktivnost"];
//Create and append select list
var selectList = document.createElement('select');
selectList.id = "mySelect";
myParent.appendChild(selectList);
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement('option');
option.value = array[i];
option.text = array[i];
selectList.appendChild(option);
}
//create remove button
var remove = document.createElement('button');
remove.onclick = function(obrisiocenu) {
removeElement(obrisiocenu);
}
remove.setAttribute("type", "dugme");
remove.innerHTML = "-"; //delete
var item = document.createElement('div')
item.classList.add("item")
item.appendChild(input);
item.appendChild(selectList);
item.appendChild(remove);
document.getElementById("stranica").appendChild(item)
}
function calcMean() {
var nameList=document.querySelectorAll('#stranica .item #mySelect');
var inputList=document.querySelectorAll('#stranica .item input');
var kontrolniList = [];
var vezbeList = [];
var aktivnostList = [];
var ocenaList = [];
for(var i=0; i< nameList.length; i++){
ocenaList.push(parseInt(inputList[i].value));
if(nameList[i].value=='Kontrolni') {
kontrolniList.push(parseInt(inputList[i].value));
}
else if(nameList[i].value=='Vezbe') {
vezbeList.push(parseInt(inputList[i].value));
}
else if(nameList[i].value=='Aktivnost') {
aktivnostList.push(parseInt(inputList[i].value));
}
}
document.getElementById("kontrolni").innerHTML=avg(kontrolniList);
document.getElementById("vezbe").innerHTML=avg(vezbeList);
document.getElementById("aktivnost").innerHTML=avg(aktivnostList);
document.getElementById("ocena").innerHTML=avg(ocenaList);
}
function avg( arr ) {
var total = 0, i;
for (i = 0; i < arr.length; i += 1) {
total += arr[i];
}
return total / arr.length;
}
<div id="stranica" style="display: inline-block; position: left;">
<button type="button" onclick="javascript:dodajocenu();"> Dodaj ocenu</button>
</div>
<div id="desna" style="display: inline-block; position: absolute; text-align: center;">
<button type="button" onclick="javascript:calcMean();"> Izracunaj prosek</button>
<br><br>
<table border="1">
<tbody>
<tr>
<td style="width:70px; text-align: center;">Kontrolni</td>
<td style="width:70px; text-align: center;">Vezbe</td>
<td style="width:70px; text-align: center;">Aktivnost</td>
</tr>
<tr>
<td id="kontrolni" style="text-align: center;"> </td>
<td id="vezbe" style="text-align: center;"></td>
<td id="aktivnost" style="text-align: center;"></td>
</tr>
</tbody>
</table>
<br>
<table border="1">
<tbody>
<tr>
<td style="width:140px; text-align: center;">Zakljucna ocena</td>
</tr>
<tr>
<td id="ocena" style="text-align: center;"> </td>
</tr>
</tbody>
</table>
</div>
Hope this will work.

Related

Set 3 values in an array - dynamic table row javascrip

I have a dynamic table and when i add a row i want to save the data from input.
I can save the data but all inside one array,i want to set just 3 values each sub array.
Because one row have 3 inputs.
But i´m having some difficulties.
I'm new to javascript and here at stack overflow
Can you help me please?
function arraySaveData() {
var data = [];
for (var index = 0; index < 1; index++) {
$('#mytableform1').each(function (_, element) {
var element = document.getElementsByName("namesavedata[]");
for (var i = 0; i < element.length; i++) {
data.push(element[i].value);
}
});
var result = [];
for(var i = 0; i < data.length; i++) {
var obj = {}
obj= data[i];
result.push(obj)
}
console.log(result)
}
}
//Button add table row
function addRow() {
var table = document.getElementById("mytableform1");
var rowCount = table.rows.length;
x = document.getElementById("mytableform1").rows.length;
var row = table.insertRow();
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
//numeração crescente
for (var i = 0; i < x; i++) {
cell1.innerHTML = '<input type="text" class="form-control" name="namesavedata[]" align="center" placeholder="' +
(cell1.innerHTML = i + 0) +
'">';
cell2.innerHTML = '<input type="text" class="form-control" name="namesavedata[]" align="center" placeholder="00000,000">';
cell3.innerHTML = '<input type="text" class="form-control" name="namesavedata[]" align="center" placeholder="00000,000">';
}
}
//Button delete table row
function deleteRow() {
var table = document.getElementById("mytableform1");
var rowCount = table.rows.length;
if (rowCount >= 4) {
table.deleteRow(rowCount - 1);
} else {
Swal.fire({
title: 'Erro!',
text: "Não pode apagar este campo",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#e55353',
cancelButtonColor: '#636f83',
confirmButtonText: 'ok'
})
}
}
<table id="mytableform1" width="100%" border="1" cellspacing="0" cellpadding="0" style="border: 1px solid;color: #5c6873;background-color: #fff;border-color: #e4e7ea;">
<tr>
<td rowspan="2" align="center" valign="top">Vértices da poligonal</td>
<td colspan="3" align="center" valign="top">Coordenadas no sistema PT - TM06/ETRS89</td>
</tr>
<tr>
<td align="center" valign="top">M(m)</td>
<td align="center" valign="top">P(m)</td>
</tr>
<tr name="allDataRow">
<td align="center" valign="top">
<input style="width: 100%;" class="form-control" type="number" name="namesavedata[]" id="val_1" placeholder="1">
</td>
<td align="center" valign="top">
<input style="width: 100%;" class="form-control" type="number" name="namesavedata[]" id="val_2" placeholder="00000,000">
</td>
<td align="center" valign="top">
<input style="width: 100%;" class="form-control" type="number" name="namesavedata[]" id="val_3" placeholder="00000,000">
</td>
</tr>
</table>
<div style="display:flex;justify-content: space-between;">
<div style="display:flex;">
<button onclick="addRow()" style="background-color: #673ab7c7;color: white;" class="btn" type="button">
<span class="bi bi-plus-square-dotted"></span>+
</button>
<button onclick="deleteRow()" style="background-color: #673ab7c7;color: white;" class="btn" type="button">
<span class="bi bi-plus-square-dotted"></span>-
</button>
</div>
<div style="display:flex;">
<button type="button" name="button" onclick="arraySaveData()" class="btn" style="background-color: #673ab7c7;color: white;">
Validar dados da tabela
</button>
</div>
</div>
Your issue is that you are creating an object and then reassigning it to the value of data[i]. This is then being pushed to your array, rather than an object, so you are getting an array of values rather than an array of objects.
Change this line of code:
var obj = {};
obj = data[i];
result.push(obj); // Add data[i] to the results array.
To this:
var obj = {data[i]};
result.push(obj); // Add an object containing data[i] to the results array
Now, you are pushing the object with the value of data[i] inside.
Or if you want to have three sub-arrays as in your question:
var tableCell = [data[i]];
result.push(tableCell);
If you run this code snippet, you can see what's happening when you reassign obj to data[i]:
const data = ["foo","bar"];
var obj = {};
console.log(obj);
// output: {}
obj = data[0];
console.log(obj);
// output: "foo"

HTML/JS output table not showing horizontal borders

I can't figure out why my horizontal borders are not showing up with my output section. See code and screenshot below:
I would like to have horizontal borders and if possible keep the date fields from
wrapping into the next row below itself.
I would like to have horizontal borders and if possible keep the date fields from wrapping into the next row below itself.
<td align="center"><input type="button" value="Submit" name="submit" id="submit" onClick="display()" /></button></td>
</tr>
</table>
<table width="400px" align="center" colspan="40" table border="5">
<tr style="background-color:#8FBC8F;">
<td align="center"><b>Name</b></td>
<td align="center"><b>Company</b></td>
<td align="center"><b>Time In</b></td>
<td align="center"><b>Time Out</b></td>
<td align="center"><b>Description of Work</b></td>
</tr>
<tr>
<td align="center"><div id="displayarea"></div></td>
<td align="center"><div id="displayarea1"></div></td>
<td align="center"><div id="displayarea2"></div></td>
<td align="center"><div id="displayarea3"></div></td>
<td align="center"><div id="displayarea4"></div></td>
</tr>
I would like to have horizontal borders and if possible keep the date fields from wrapping into the next row below itself.
function getValue() {
var Items = "";
var td1 = document.getElementById("displayarea").innerHTML.split("<br>");
var td2 = document.getElementById("displayarea1").innerHTML.split("<br>");
var td3 = document.getElementById("displayarea2").innerHTML.split("<br>");
var td4 = document.getElementById("displayarea3").innerHTML.split("<br>");
var td5 = document.getElementById("displayarea4").innerHTML.split("<br>");
for (var i = 0; i < td1.length; i++) {
if (td1[i])
Items += td1[i] + " ,";
if (td2[i])
Items += td2[i] + " ,";
if (td2[i])
Items += td2[i] + " ,";
if (td3[i])
Items += td3[i] + " ,";
if (td4[i])
Items += td4[i] + " ";
Items += "\n";
}
console.log(Items);
return Items;
}
function display() {
document.getElementById("displayarea").innerHTML += document.getElementById("fname").value + "<br />";
document.getElementById("fname").value = "";
document.getElementById("displayarea1").innerHTML += document.getElementById("lname").value + "<br />";
document.getElementById("lname").value = "";
document.getElementById("displayarea2").innerHTML += document.getElementById("sname").value + "<br />";
document.getElementById("sname").value = "";
document.getElementById("displayarea3").innerHTML += document.getElementById("pname").value + "<br />";
document.getElementById("pname").value = "";
document.getElementById("displayarea4").innerHTML += document.getElementById("jname").value + "<br />";
document.getElementById("jname").value = "";
}
I highly suggest you start separating your data from your presentation of that data.
So, split your display function into two: createRow and renderRows. Likewise, getValues can just be getRows.
Note that this required a different way of doing things in your code, so I also refactored your HTML and CSS to bring it more in line with modern methods.
function getRows(data) {
return data.map(datum => Object.values(datum).join(',')).join('\n');
}
function createRow(data) {
const datum = {
fname: document.getElementById("fname").value,
lname: document.getElementById("lname").value,
sname: new Date(document.getElementById("sname").valueAsNumber).toLocaleString(),
pname: new Date(document.getElementById("pname").valueAsNumber).toLocaleString(),
jname: document.getElementById("jname").value
};
data.push(datum);
document.getElementById("dataForm").reset();
renderRows(data);
}
function renderRows(data) {
const body = document.getElementById("renderedData");
body.innerHTML = "";
for (let datum of data) {
let tr = document.createElement('tr');
let tdFName = document.createElement('td');
tdFName.appendChild(document.createTextNode(datum.fname));
tr.appendChild(tdFName);
let tdLName = document.createElement('td');
tdLName.appendChild(document.createTextNode(datum.lname));
tr.appendChild(tdLName);
let tdSName = document.createElement('td');
tdSName.appendChild(document.createTextNode(datum.sname));
tr.appendChild(tdSName);
let tdPName = document.createElement('td');
tdPName.appendChild(document.createTextNode(datum.pname));
tr.appendChild(tdPName);
let tdJName = document.createElement('td');
tdJName.appendChild(document.createTextNode(datum.jname));
tr.appendChild(tdJName);
body.appendChild(tr);
}
}
window.addEventListener('load', () => {
const data = [];
document.getElementById('add').addEventListener('click', function(e) {
createRow(data);
});
document.getElementById('getData').addEventListener('click', function(e) {
console.log(getRows(data));
});
});
form {
width: max-content;
margin: 0 auto 1rem;
}
.control-group {
display: flex;
justify-content: space-between;
}
fieldset {
display: flex;
flex-flow: column nowrap;
}
fieldset button {
align-self: flex-end;
}
<form id="dataForm">
<fieldset>
<legend>Enter Data</legend>
<div class="control-group">
<label for="fname">Name:</label>
<input id="fname" type="text">
</div>
<div class="control-group">
<label for="lname">Company:</label>
<input id="lname" type="text">
</div>
<div class="control-group">
<label for="sname">Time In:</label>
<input id="sname" type="datetime-local">
</div>
<div class="control-group">
<label for="pname">Time Out:</label>
<input id="pname" type="datetime-local">
</div>
<div class="control-group">
<label for="jname">Description of Work:</label>
<textarea id="jname"></textarea>
</div>
<button type="button" id="add">Add</button>
</fieldset>
</form>
<table width="400px" align="center" colspan="40" table border="5">
<thead>
<tr style="background-color:#8FBC8F;" id='header'>
<td align="center"><b>Name</b></td>
<td align="center"><b>Company</b></td>
<td align="center"><b>Time In</b></td>
<td align="center"><b>Time Out</b></td>
<td align="center"><b>Description of Work</b></td>
</tr>
</thead>
<tbody id="renderedData">
</tbody>
</table>
<button type="button" id="getData">Get Data</button>
To get borders for all cells, add this at the top of your html code (inside the head):
<style>
table {
border-collapse: collapse;
}
td {
border: 1px solid #555;
}
</style>
Adjust the border thickness, style and color as you like (in the border setting of td)
Here's an easy way to add a row with each addition using the element - available in all good browsers (not so fast Internet Explorer, I wasn't talking to you)
I've also changed how to read the values
note, using class instead of id in the cells in the rows - to make it easy to get them all with minimal change to your code
Although, personally I'd get the row data data differently (shown in alternativeGetValues)
function getValue() {
var Items = "";
var td1 = [...document.querySelectorAll(".displayarea")].map(e => e.innerHTML);
var td2 = [...document.querySelectorAll(".displayarea1")].map(e => e.innerHTML);
var td3 = [...document.querySelectorAll(".displayarea2")].map(e => e.innerHTML);
var td4 = [...document.querySelectorAll(".displayarea3")].map(e => e.innerHTML);
var td5 = [...document.querySelectorAll(".displayarea4")].map(e => e.innerHTML);
for (var i = 0; i < td1.length; i++) {
if (td1[i])
Items += td1[i] + " ,";
if (td2[i])
Items += td2[i] + " ,";
if (td3[i])
Items += td3[i] + " ,";
if (td4[i])
Items += td4[i] + " ,";
if (td5[i])
Items += td5[i] + " ";
Items += "\n";
}
console.log(Items);
return Items;
}
function display() {
const template = document.getElementById("row");
const clone = template.content.cloneNode(true);
const additem = (dest, src) => {
const s = document.querySelector(src);
clone.querySelector(dest).innerHTML = s.value;
s.value = "";
};
additem(".displayarea", "#fname");
additem(".displayarea1", "#lname");
additem(".displayarea2", "#sname");
additem(".displayarea3", "#pname");
additem(".displayarea4", "#jname");
template.insertAdjacentElement('beforebegin', clone.firstElementChild);
}
// IMHO this is better
function alternateGetValue() {
const Items = [...document.querySelectorAll('.data')]
.map(row => [...row.querySelectorAll('td>div')]
.map(d => d.textContent).join(',')
).join('\n');
console.log(Items);
return Items;
}
.wide {
min-width:12em;
}
F: <input id="fname"> <br>
L: <input id="lname"> <br>
S: <input id="sname"> <br>
P: <input id="pname"> <br>
J: <input id="jname"> <br>
<input type="button" value="add" onclick="display()"/>
<input type="button" value="show" onclick="getValue()"/>
<input type="button" value="Better" onclick="alternateGetValue()"/>
<table width="400px" align="center" colspan="40" table border="5">
<thead>
<tr style="background-color:#8FBC8F;" id='header'>
<td align="center"><b>Name</b></td>
<td align="center"><b>Company</b></td>
<td align="center" class="wide"><b>Time In</b></td>
<td align="center" class="wide"><b>Time Out</b></td>
<td align="center"><b>Description of Work</b></td>
</tr>
</thead>
<tbody>
<template id="row">
<tr style="background-color:#8F8FBC;" class="data">
<td align="center"><div class="displayarea"></div></td>
<td align="center"><div class="displayarea1"></div></td>
<td align="center"><div class="displayarea2"></div></td>
<td align="center"><div class="displayarea3"></div></td>
<td align="center"><div class="displayarea4"></div></td>
</tr>
</template>
</tbody>
</table>

Having trouble with onclick displaying and hiding differnt text

I have a table where the text in column on the left can be clicked and the text in the column on the right will change accordingly. The way it should work is when one of the options on the left is clicked, only the text on the right that corresponds to the selected option appears. However, when I click one of my options on the left it just hides all of the text on the right and does not display the part I want to see.
var selectColor = function( element ) {
/* Change color of text based on current selection */
prots = document.getElementsByClassName( "prot_id" );
for ( i = 0; i < prots.length; ++i ) {
prots.item(i).style.color = 'black';
element.style.color = 'red';
}
}
var selectProtein = function( element ) {
/* Change what info is displayed based on current selection */
var proteinInfo = document.getElementsByClassName( "prot_func" ) ;
for( j = 0; j < proteinInfo.length; ++j ) {
proteinInfo[j].style['display'] = 'none' ;
}
var proteinIDs = ["gria1", "gria2", "gria3", "gria4"] ;
proteinIDs.forEach(function(entry) {
if( element.src.includes(entry)) {
var theProtein = document.getElementById(entry) ;
theProtein.style['display'] = 'block' ;
}
})
}
<head>
<link rel='stylesheet' type='text/css' href='./index.css'>
</head>
<body>
<table>
<tr>
<td>
<p class="prot_id" onclick="selectColor(this); selectProtein(this)">GRIA1_HUMAN</p>
<p class="prot_id" onclick="selectColor(this); selectProtein(this)">GRIA2_HUMAN</p>
<p class="prot_id" onclick="selectColor(this); selectProtein(this)">GRIA3_HUMAN</p>
<p class="prot_id" onclick="selectColor(this); selectProtein(this)">GRIA4_HUMAN</p>
</td>
<td>
<p id="gria1" class="prot_func">...</p>
<p id="gria2" class="prot_func">...</p>
<p id="gria3" class="prot_func">...</p>
<p id="gria4" class="prot_func">...</p>
</td>
</tr>
</table>
</body>
There are a few issues that you are having so I updated your code.
I got rid of onclick and went with an event handler instead.
I got rid of the protein array loop and just added each id as a data attribute to the paragraph tags.
Instead of hiding/showing based on the style, I just add/remove a class instead.
var selectColor = function(element) {
/* Change color of text based on current selection */
prots = document.getElementsByClassName("prot_id");
for (i = 0; i < prots.length; ++i) {
prots.item(i).classList.remove("active");
}
element.classList.add("active")
}
var selectProtein = function(element) {
var proteinInfo = document.getElementsByClassName("prot_func");
for (j = 0; j < proteinInfo.length; ++j) {
proteinInfo[j].classList.remove("active");
}
theProtein = document.querySelector("#" + element.dataset.id);
theProtein.classList.add("active");
}
document.querySelectorAll(".prot_id").forEach(function(el) {
el.addEventListener("click", function(e) {
selectColor(e.target);
selectProtein(e.target)
});
});
.prot_func {
display: none;
}
.prot_func.active {
display: block;
}
.prot_id.active {
color: red;
}
<table>
<tr>
<td>
<p class="prot_id" data-id="gria1">GRIA1_HUMAN</p>
<p class="prot_id" data-id="gria2">GRIA2_HUMAN</p>
<p class="prot_id" data-id="gria3">GRIA3_HUMAN</p>
<p class="prot_id" data-id="gria4">GRIA4_HUMAN</p>
</td>
<td>
<p id="gria1" class="prot_func">.1..</p>
<p id="gria2" class="prot_func">.2..</p>
<p id="gria3" class="prot_func">.3..</p>
<p id="gria4" class="prot_func">..4.</p>
</td>
</tr>
</table>
From your snippet, you are going to show the options on the right side based on the selected p tag content.
So if GRIA1_HUMAN is selected, gria1 should be shown.
You can get the value of p content using innerText attribute and compare the values using it. I have attached the working example.
var selectColor = function (element) {
/* Change color of text based on current selection */
prots = document.getElementsByClassName("prot_id");
for ( i = 0; i < prots.length; ++i ) {
prots.item(i).style.color = 'black';
}
element.style.color = 'red';
}
var selectProtein = function (element) {
/* Change what info is displayed based on current selection */
var proteinInfo = document.getElementsByClassName("prot_func") ;
for( j = 0; j < proteinInfo.length; ++j) {
proteinInfo[j].style['display'] = 'none' ;
}
var proteinIDs = ["gria1", "gria2", "gria3", "gria4"] ;
const elementText = element.innerText.toLowerCase();
proteinIDs.forEach(function(entry) {
if(elementText.includes(entry)) {
var theProtein = document.getElementById(entry);
theProtein.style['display'] = 'block';
}
});
}
<table border="1">
<tr>
<td>
<p class="prot_id" onclick="selectColor(this); selectProtein(this)">GRIA1_HUMAN</p>
</td>
<td>
<p id="gria1" class="prot_func">...</p>
</td>
</tr>
<tr>
<td><p class="prot_id" onclick="selectColor(this); selectProtein(this)">GRIA2_HUMAN</p></td>
<td><p id="gria2" class="prot_func">...</p></td>
</tr>
<tr>
<td><p class="prot_id" onclick="selectColor(this); selectProtein(this)">GRIA3_HUMAN</p></td>
<td><p id="gria3" class="prot_func">...</p></td>
</tr>
<tr>
<td><p class="prot_id" onclick="selectColor(this); selectProtein(this)">GRIA4_HUMAN</p></td>
<td><p id="gria4" class="prot_func">...</p></td>
</tr>
</table>

Can't set HTML field from JS variable?

Trying to click on an HTML cell and grab that cell's html data, stick it into a form field to be used in a latter process. I can set this fields value to anything I want if I code it directly like: blah = 99; however if I change that hard value to a variable or to the cell contents it doesn't work. I can alert it all day long, I just cannot for the life of me get the value to go to the form field. What am I missing?
var tbl = document.getElementById("tblMain");
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function () {
getval(this);
};
}
}
function getval(cel) {
var theTarget;
theTarget = cel.innerHTML;
document.getElementById("status").value = cel.innerHTML;
}
<center>
Click on below table cell to find its value.
<br />
</center>
<table align="center" id="tblMain" border="1" style="cursor: pointer;">
<tr>
<td>
R1C1
</td>
<td>
R1C2
</td>
<td>
R1C3
</td>
<td>
R1C4
</td>
</tr>
</table><br><br>
<p align="center"><input name="status" type="text" id="status" style="color: #000; border: #000 1px solid;" size="5">
</p>
It works. It's just that the innerHTML has too much white space around the actual text. Use trim() to get rid of it.
<html>
<head>
<title>Find table cell value on cell (table) click using JavaScript</title>
</head>
<body>
<center>
Click on below table cell to find its value.
<br />
</center>
<table align="center" id="tblMain" border="1" style="cursor: pointer;">
<tr>
<td>
R1C1
</td>
<td>
R1C2
</td>
<td>
R1C3
</td>
<td>
R1C4
</td>
</tr>
</table><br><br>
<p align="center"><input name="status" type="text" id="status" style="color: #000; border: #000 1px solid;" size="5">
</p>
<script language="javascript">
var tbl = document.getElementById("tblMain");
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function () {
getval(this); };
}
}
function getval(cel) {
var theTarget;
theTarget = cel.innerHTML;
document.getElementById("status").value = cel.innerHTML.trim();
}
</script>
</body>
</html>
You can use regular expression to remove spaces before and after the string cel.innerHTML.replace(/^\s+|\s+$/g,''); , this will be supported in dinosaur browser that don't support trim()
var tbl = document.getElementById("tblMain");
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function () { getval(this); };
}
}
function getval(cel) {
var theTarget;
theTarget = cel.innerHTML;
document.getElementById("status").value = cel.innerHTML.replace(/\s/g, "");
}
<center>
Click on below table cell to find its value.
<br />
</center>
<table align="center" id="tblMain" border="1" style="cursor: pointer;">
<tr>
<td>
R1C1
</td>
<td>
R1C2
</td>
<td>
R1C3
</td>
<td>
R1C4
</td>
</tr>
</table><br><br>
<p align="center"><input name="status" type="text" id="status" style="color: #000; border: #000 1px solid;" size="5">
</p>

JS How to calculate the values of rows in a table?

For example, there is such a table, with cells FootballPlayers, Swimmers, BasketballPlayers and Sum, in which rows are added in turn, how i can count and record in the Total row how many football players, swimmers and basketball players are added?
function deleteRow() {
tg.deleteRow(1);
if (document.all("tg").rows.length == 2) {
document.getElementById("b").disabled=true;
}
}
function addRow() {
var f1 = document.getElementById("f1").value;
var f1k = parseInt(f1);
if (isNaN(f1k)) {
f1k=0;
}
var f2 = document.getElementById("f2").value;
var f2k = parseInt(f2);
if (isNaN(f2k)) {
f2k=0;
}
var f3 = document.getElementById("f3").value;
var f3k = parseInt(f3);
if (isNaN(f3k)) {
f3k=0;
}
var sum1 = (f1k+f2k+f3k);
var row = document.createElement("TR")
var tbody = document.getElementById("tg").insertRow(1);
var r1=tbody.insertCell(0);
r1.innerHTML="";
var r2=tbody.insertCell(1);
r2.innerHTML=f1;
var r3=tbody.insertCell(2);
r3.innerHTML=f2;
var r4=tbody.insertCell(3);
r4.innerHTML=f3;
var r4=tbody.insertCell(4);
r4.innerHTML=sum1;
if(document.all("tg").rows.length >= 3) {
document.getElementById("b").disabled=false;
}
}
#tg {border-collapse:collapse;border-spacing:0;}
#tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
#tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
#tg .tg-yw4l{vertical-align:top}
<div class="row">
<label for="n">FootballPlayers: </label>
<input type="text" id="f1" />
</div>
<div class="row">
<label for="n">Swimmers: </label>
<input type="text" id="f2" />
</div>
<div class="row">
<label for="n">BasketballPlayers: </label>
<input type="text" id="f3" />
<button id="a" onClick="addRow();return false;" >Add</button>
<button id="b" onClick="deleteRow();return false;">Delete</button>
</div>
<table id="tg">
<tr>
<th class="tg-031e"></th>
<th class="tg-031e">FootballPlayers</th>
<th class="tg-031e">Swimmers</th>
<th class="tg-yw4l">BasketballPlayers</th>
<th class="tg-yw4l">Sum</th>
</tr>
<tr>
<td class="tg-031e">Total</td>
<td class="tg-031e"></td>
<td class="tg-031e"></td>
<td class="tg-yw4l"></td>
<td class="tg-yw4l"></td>
</tr>
</table>
Here is an example, only total FootballPlayers
Step 1)
Add a class for FootballPlayers column when you add a row
Step 2)
Call total() javascript function while add a row and delete a row
<div class="row">
<label for="n">FootballPlayers: </label>
<input type="text" id="f1" />
</div>
<div class="row">
<label for="n">Swimmers: </label>
<input type="text" id="f2" />
</div>
<div class="row">
<label for="n">BasketballPlayers: </label>
<input type="text" id="f3" />
<button id="a" onClick="addRow();return false;" >Add</button>
<button id="b" onClick="deleteRow();return false;">Delete</button>
</div>
<table id="tg">
<tr>
<th class="tg-031e"></th>
<th class="tg-031e">FootballPlayers</th>
<th class="tg-031e">Swimmers</th>
<th class="tg-yw4l">BasketballPlayers</th>
<th class="tg-yw4l sum">Sum</th>
</tr>
<tr>
<td class="tg-031e">Total</td>
<td class="tg-031e total_fb_players"></td>
<td class="tg-031e total_summers"></td>
<td class="tg-yw4l total_bb_players"></td>
<td class="tg-yw4l total_sum"></td>
</tr>
</table>
<style>
#tg {border-collapse:collapse;border-spacing:0;}
#tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
#tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
#tg .tg-yw4l{vertical-align:top}
</style>
<script>
function deleteRow() {
tg.deleteRow(1);
if (document.all("tg").rows.length == 2) {
document.getElementById("b").disabled=true;
}
total();
}
function addRow() {
var f1 = document.getElementById("f1").value;
var f1k = parseInt(f1);
if (isNaN(f1k)) {
f1k=0;
}
var f2 = document.getElementById("f2").value;
var f2k = parseInt(f2);
if (isNaN(f2k)) {
f2k=0;
}
var f3 = document.getElementById("f3").value;
var f3k = parseInt(f3);
if (isNaN(f3k)) {
f3k=0;
}
var sum1 = (f1k+f2k+f3k);
var row = document.createElement("TR")
var tbody = document.getElementById("tg").insertRow(1);
var r1=tbody.insertCell(0);
r1.innerHTML="";
var r2=tbody.insertCell(1);
r2.classList.add('fb_players')
r2.innerHTML=f1;
var r3=tbody.insertCell(2);
r3.classList.add('summers')
r3.innerHTML=f2;
var r4=tbody.insertCell(3);
r4.classList.add('bb_players')
r4.innerHTML=f3;
var r5=tbody.insertCell(4);
r5.classList.add('sum')
r5.innerHTML=sum1;
if(document.all("tg").rows.length >= 3) {
document.getElementById("b").disabled=false;
}
total();
}
function total() {
var fb_players = document.getElementsByClassName("fb_players");
var total_fb_players = 0;
for(var i = 0; i < fb_players.length; i++) {
var v = parseInt(fb_players[i].innerHTML);
if (isNaN(v)) {
v=0;
}
console.log(v);
total_fb_players += v;
}
console.log(total_fb_players);
var total_fb_players_html = document.querySelector(".total_fb_players");
total_fb_players_html.innerHTML=total_fb_players;
}
</script>
Add classes to your cells and ids to for each total column in your table and execute as follows
Snippet below
function deleteRow() {
tg.deleteRow(1);
if (document.all("tg").rows.length == 2) {
document.getElementById("b").disabled = true;
}
}
function addRow() {
var f1 = document.getElementById("f1").value;
var f1k = parseInt(f1);
if (isNaN(f1k)) {
f1k = 0;
}
var f2 = document.getElementById("f2").value;
var f2k = parseInt(f2);
if (isNaN(f2k)) {
f2k = 0;
}
var f3 = document.getElementById("f3").value;
var f3k = parseInt(f3);
if (isNaN(f3k)) {
f3k = 0;
}
var sum1 = (f1k + f2k + f3k);
var row = document.createElement("TR")
var tbody = document.getElementById("tg").insertRow(1);
var r1 = tbody.insertCell(0);
r1.innerHTML = "";
var r2 = tbody.insertCell(1);
r2.innerHTML = f1;
r2.className = "football";
var r3 = tbody.insertCell(2);
r3.innerHTML = f2;
r3.className = "swimmer";
var r4 = tbody.insertCell(3);
r4.innerHTML = f3;
r4.className = "basketball";
var r4 = tbody.insertCell(4);
r4.innerHTML = sum1;
if (document.all("tg").rows.length >= 3) {
document.getElementById("b").disabled = false;
}
var football_el = document.getElementsByClassName("football");
var swim_count_el = document.getElementsByClassName("swimmer");
var basketball_el = document.getElementsByClassName("basketball");
var list = [football_el, swim_count_el, basketball_el];
grand_sum = 0;
for (var y = 0; y < list.length; ++y) {
var sum = 0;
for (var x = 0; x < list[y].length; ++x) {
sum += Number(list[y][x].innerHTML);
}
if (y == 0) {
document.getElementById("total_footballers").innerHTML = sum;
grand_sum += sum;
} else if (y == 1) {
document.getElementById("total_swimmers").innerHTML = sum;
grand_sum += sum;
} else if (y == 2) {
document.getElementById("total_basketballers").innerHTML = sum;
grand_sum += sum;
}
} //end for
document.getElementById("grandtotal").innerHTML = grand_sum;
}
#tg {
border-collapse: collapse;
border-spacing: 0;
}
#tg td {
font-family: Arial, sans-serif;
font-size: 14px;
padding: 10px 5px;
border-style: solid;
border-width: 1px;
overflow: hidden;
word-break: normal;
}
#tg th {
font-family: Arial, sans-serif;
font-size: 14px;
font-weight: normal;
padding: 10px 5px;
border-style: solid;
border-width: 1px;
overflow: hidden;
word-break: normal;
}
#tg .tg-yw4l {
vertical-align: top
}
<div class="row">
<label for="n">FootballPlayers: </label>
<input type="text" id="f1" />
</div>
<div class="row">
<label for="n">Swimmers: </label>
<input type="text" id="f2" />
</div>
<div class="row">
<label for="n">BasketballPlayers: </label>
<input type="text" id="f3" />
<button id="a" onClick="addRow();return false;">Add</button>
<button id="b" onClick="deleteRow();return false;">Delete</button>
</div>
<table id="tg">
<tr>
<th class="tg-031e"></th>
<th class="tg-031e">FootballPlayers</th>
<th class="tg-031e">Swimmers</th>
<th class="tg-yw4l">BasketballPlayers</th>
<th class="tg-yw4l">Sum</th>
</tr>
<tr>
<td class="tg-031e">Total</td>
<td class="tg-031e" id="total_footballers"></td>
<td class="tg-031e" id="total_swimmers"></td>
<td class="tg-yw4l" id="total_basketballers"></td>
<td class="tg-yw4l" id="grandtotal"></td>
</tr>
</table>

Categories