I have a form to enter scores and calculate the average score. After entering the form, the user clicks on the submit button, it will display a table of scores that have been entered before along with 2 buttons. First button will add a column of average scores to the form and the second button will determine if any average score is >= 8 the letter in that column will be highlighted in red.
Here is my code.
Here is my HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="css/main.css" />
</head>
<body>
<script src="js/script.js"></script>
<h1 align="center">Class Marksheet</h1>
<!--
This is a form for users to enter scores
-->
<table align="center">
<tr>
<td>Name:</td>
<td><input name="name" id="name" type="text" /></td>
</tr>
<tr>
<td>Math:</td>
<td><input name="math" id="math" type="text" /></td>
</tr>
<tr>
<td>Physics:</td>
<td><input name="physics" id="physics" type="text" /></td>
</tr>
<tr>
<td>Chemistry:</td>
<td><input name="chemical" id="chemical" type="text" /></td>
</tr>
<td>
<button type="submit" onclick="score_table()">Submit</button>
</td>
</table>
<!--
This table below must not show when user access the browser,
it only show after user enter score and click the "Submit" button with 2 button below
-->
<table id="tableScore" border="2" width="100%">
<th>No</th>
<th>Name</th>
<th>Math</th>
<th>Physics</th>
<th>Chemistry</th>
<th>Average Score</th> <!-- This still can not show -->
</table>
<div>
<button onclick="">Show the average score</button> <!--This will show the average score column-->
<button onclick="">Best student</button> <!--Determine if any average score >= 8 hightlight all the text into red-->
</div>
</body>
</html>
My JS file:
var testScore = {
name: "",
math: 0,
physical: 0,
chemistry: 0
};
var i = 0; /* This variable is incremented by 1 every time the user clicks the "Submit" button. Display the "No" column, and the position of rows when added to the table
*/
// Show a table after submit
function score_table() {
document.getElementById("tableScore").style.display="block";
// Gathering the data after submit
testScore.name = document.getElementById("name").value;
testScore.math = document.getElementById("math").value;
testScore.physical = document.getElementById("physics").value;
testScore.chemistry = document.getElementById("chemical").value;
testScore.avg = "?";
document.getElementById("name").value = "";
document.getElementById("math").value = "";
document.getElementById("physics").value = "";
document.getElementById("chemical").value = "";
// Insert row
var table = document.getElementById("tableScore");
var row = table.insertRow();
var number = row.insertRow();
var name = row.insertRow();
var math = row.insertRow();
var physics = row.insertRow();
var chemistry = row.insertRow();
var avg = row.insertRow();
number.innerHtml = i;
name.innerHtml = testScore.name;
math.innerHtml = testScore.math;
physics.innerHtml = testScore.physics;
chemistry.innerHtml = testScore.chemistry;
avg.innerHtml = "?";
/** I need help, How to calculate the average score and if the average
score is >= 8 then hightlight every text in that row into red
*/
}
Finally, my CSS file:
/* I just do to hidden the table, because i struggle with JS file :)) */
#tableScore {
display: none;
}
There are a few problems with your source code.1. you used testScore.avg, but you did not declare avg in the variable testScore.2.it is better to use type="number" as the input for the scores, or you need to add pattern="yourpattern" to disallow input of alphabets and special characters.3.innerHtml is not the correct syntax, use innerHTML instead.4.You only need to use one insertRow().As for the other fields, you should use insertCell()instead.5.You need to insert a number into the insertRow/insertCell method. Eg.insertRow(x);
As for calculating the average, you can easily find it by adding the three fields and dividing them by the number of fields.It is also better to hide the whole division instead of just the table, don't you think it's weird that you have button in the website but it does nothing?You can also add the input fields inside a form, so that you can add mandatory attribute to the fields to ensure no null values will be added into the table. You also need to add i++; in your function, otherwise all the numbers in the column "No" of your table will be the same number.To hide/show a certain column in the table, you can use nth-child in the css/js.Last and the most important issue, check your spelling. Some you use physics, some use physical, some use chemistry, but some use chemical, this is very confusing and will bring a hard time during maintenance or debugging in the future. You can also easily encounter a lot of errors this way. Eg. you declared as testScore.physical, but in the function you used testScore.physicsChoose one variable name and stick with it.
var testScore = {
name: "",
math: 0,
physics: 0,
chemistry: 0,
avg: 0
};
var i = 1;
/* This variable is incremented by 1 every time the user clicks the "Submit" button. Display the "No" column, and the position of rows when added to the table
*/
// Show a table after submit
function score_table() {
document.getElementById("divTable").style.display = "block";
// Gathering the data after submit
testScore.name = document.getElementById("name").value;
testScore.math = document.getElementById("math").value;
testScore.physics = document.getElementById("physics").value;
testScore.chemistry = document.getElementById("chemical").value;
testScore.avg = (parseFloat(testScore.math) + parseFloat(testScore.physics) + parseFloat(testScore.chemistry)) / 3;
document.getElementById("name").value = "";
document.getElementById("math").value = "";
document.getElementById("physics").value = "";
document.getElementById("chemical").value = "";
// Insert row
var table = document.getElementById("tableScore");
var row = table.insertRow(i);
var number = row.insertCell(0);
var name = row.insertCell(1);
var math = row.insertCell(2);
var physics = row.insertCell(3);
var chemistry = row.insertCell(4);
var avg = row.insertCell(5);
number.innerHTML = i;
name.innerHTML = testScore.name;
math.innerHTML = testScore.math;
physics.innerHTML = testScore.physics;
chemistry.innerHTML = testScore.chemistry;
avg.innerHTML = testScore.avg;
i++;
/** I need help, How to calculate the average score and if the average
score is >= 8 then hightlight every text in that row into red
*/
}
function showAvg() {
document.getElementById("tableScore").querySelector("th:nth-child(6)").style.display = "block";
var colAvg = document.getElementById("tableScore").querySelectorAll("td:nth-child(6n)");
for (var i = 0; i < colAvg.length; i++) {
colAvg[i].style.display = "block";
}
}
function showBest() {
var colAvg = document.getElementById("tableScore").querySelectorAll("td:nth-child(6n)");
var rowAvg = document.getElementById("tableScore").querySelectorAll("tr:nth-child(1n)");
for (var i = 0; i < colAvg.length; i++) {
var avg = parseFloat(colAvg[i].innerText);
if (avg >= 8) {
rowAvg[i + 1].style.background = "red";
} else {}
}
}
/* I just do to hidden the table, because i struggle with JS file :)) */
#divTable {
display: none;
width: 100%;
}
#tableScore th:nth-child(6),
#tableScore td:nth-child(6) {
display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="css/main.css" />
</head>
<body>
<script src="js/script.js"></script>
<h1 align="center">Class Marksheet</h1>
<!--
This is a form for users to enter scores
-->
<table align="center">
<tr>
<td>Name:</td>
<td><input name="name" id="name" type="text" /></td>
</tr>
<tr>
<td>Math:</td>
<td><input name="math" id="math" type="number" /></td>
</tr>
<tr>
<td>Physics:</td>
<td><input name="physics" id="physics" type="number" /></td>
</tr>
<tr>
<td>Chemistry:</td>
<td><input name="chemical" id="chemical" type="number" /></td>
</tr>
<td>
<button type="submit" onclick="score_table()">Submit</button>
</td>
</table>
<!--
This table below must not show when user access the browser,
it only show after user enter score and click the "Submit" button with 2 button below
-->
<div id="divTable">
<table id="tableScore" border="2">
<th>No</th>
<th>Name</th>
<th>Math</th>
<th>Physics</th>
<th>Chemistry</th>
<th>Average Score</th>
<!-- This still can not show -->
</table>
<button onclick="showAvg()">Show the average score</button>
<!--This will show the average score column-->
<button onclick="showBest()">Best student</button>
<!--Determine if any average score >= 8 hightlight all the text into red-->
</div>
</body>
</html>
Related
A billing form
I am trying to make a billing form where I need to automatically show amount generated after entering values for price and quantity columns. But with the following code I am only able to calculate it for one row. I want it to work for every row each time I entry values to it and at the end, it should display sum total of the amount column also.
function deleteRow(row)
{
var i=row.parentNode.parentNode.rowIndex;
document.getElementById('billingSheet').deleteRow(i);
}
function addRow(){
var x=document.getElementById('billingSheet');
// deep clone the targeted row
var new_row = x.rows[1].cloneNode(true);
// get the total number of rows
var len = x.rows.length;
// set the innerHTML of the first row
new_row.cells[0].innerHTML = len;
// grab the input from the first cell and update its ID and value
var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = '';
// grab the input from the second cell and update its ID and value
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = '';
// grab the input from the third cell and update its ID and value
var inp3 = new_row.cells[3].getElementsByTagName('input')[0];
inp3.id += len;
inp3.value = '';
// append the new row to the table
x.appendChild( new_row );
}
function calc(){
$('#input1,#input2').keyup(function(){
var textValue1 =$('#input1').val();
var textValue2 = $('#input2').val();
$('#output').val(textValue1 * textValue2);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="billingSheet" border="1" width="65%">
<tr>
<th>Serial No</th>
<th>Enter item name</th>
<th> Price </th>
<th> Quantity </th>
<th> Amount</th>
<th>Add</th>
<th>Delete</th>
</tr>
<tr>
<td>1</td>
<td><input type="text"></td>
<td><input type="number" name="input1" id="input1" onkeyup="calc()"></td>
<td><input type="number" name="input2" id="input2" onkeyup="calc()"></td>
<td><input type="text" name="output" id="output" value=""></td>
<td><input type="button" id="add" value="Add Row" onClick="addRow()"/></td>
<td><input type="button" id="delete" value="Delete Row" onclick="deleteRow(this)"></td>
</tr>
</table>
function deleteRow(row) {
var i = row.parentNode.parentNode.rowIndex;
document.getElementById('billingSheet').deleteRow(i);
}
var input1 = "";
function addRow() {
var x = document.getElementById('billingSheet');
// deep clone the targeted row
var new_row = x.rows[1].cloneNode(true);
// get the total number of rows
var len = x.rows.length;
// set the innerHTML of the first row
new_row.cells[0].innerHTML = len;
// grab the input from the first cell and update its ID and value
var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = '';
// grab the input from the second cell and update its ID and value
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.id += len;
inp2.name = len;
inp2.value = '';
// grab the input from the third cell and update its ID and value
var inp3 = new_row.cells[3].getElementsByTagName('input')[0];
inp3.id += len;
inp3.name = len;
inp3.value = '';
// grab the input from the third cell and update its ID and value
var inp4 = new_row.cells[4].getElementsByTagName('input')[0];
inp4.id = "output" + len;
inp4.value = '';
// append the new row to the table
x.appendChild(new_row);
}
function calc(input, name) {
if (!input.value || isNaN(input.value))
return;
var str = input.id.substr(6, input.id.length);
var textValue1 = $('#input1' + str).val();
var textValue2 = $('#input2' + str).val();
$('#output' + name).val(textValue1 * textValue2);
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page Title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="billingSheet" border="1" width="65%">
<tr>
<th>Serial No</th>
<th>Enter item name</th>
<th> Price </th>
<th> Quantity </th>
<th> Amount</th>
<th>Add</th>
<th>Delete</th>
</tr>
<tr>
<td>1</td>
<td><input type="text"></td>
<td><input type="number" name ="1" id="input1" onkeyup="calc(this,name)"></td>
<td><input type="number" name ="1" id="input2" onkeyup="calc(this,name)"></td>
<td><input type="text" name="output1" id="output1" value=""></td>
<td><input type="button" id="add" value="Add Row" onClick="addRow()"/></td>
<td><input type="button" id="delete" value="Delete Row" onclick="deleteRow(this)"></td>
</tr>
</table>
</body>
<script src="js/index.js"></script>
</html>
I tried to do multiplication of two fields, but I want to take the result minus the third field (I want to get the different in column of credit).
$.fn.fonkTopla = function() {
var toplam = 1;
this.each(function() {
var deger = fonkDeger($(this).val());
toplam *= deger;
});
return toplam;
};
function fonkDeger(veri) {
return (veri != '') ? parseInt(veri) : 1;
}
$(document).ready(function() {
$('input[name^="fiyat"]').bind('keyup', function() {
$('#toplam').html($('input[name^="fiyat"]').fonkTopla());
});
});
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-9" />
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div id="kapsayici">
<ul>
<table border="1">
<tr>
<th>Type</th>
<th>Quantity</th>
<th>Unit Price</th>
<th>Total</th>
<th>Paid</th>
<th>Credit</th>
</tr>
<tr>
<td><input type="text" name="" value="ItemCode" class="mytext" /></td>
<td><input type="text" name="fiyat[]" class="mytext" /></td>
<td><input type="text" name="fiyat[]" class="mytext" /></td>
<td><span id="toplam"></span> RWF</td>
<td><input type="text" name="fiyat[]" class="mytext" /></td>
<td><span id="toplam_difference_here"></span> RWF</td>
</tr>
</table>
</ul>
</div>
</body>
</html>
The result will be in the following column
<td><span id="toplam_difference_here"></span> RWF</td>
Add data attr 'noaction' and class 'paid; within the third input paid field
<!-- add data attr noaction and class paid within paid field-->
<td><input type="text" name="fiyat[]" data-noaction="true" class="paid mytext" /></td>
On based on data attribute, if the input field is paid, do not multiply.
$.fn.fonkTopla = function() {
var toplam = 1;
this.each(function() {
var deger = fonkDeger($(this).val());
//get the data attr value
var no_action= $(this).data('noaction');
var paid_val = $(this).closest('tr').find('.paid').val();
//On based on data attribute, if the input field is paid, do not multiply,
if(!no_action){
toplam *= deger;
//take the result minus paid field
total = toplam - paid_val;
}
});
return total;
};
DEMO
Based on comments modify the code.
In form use class instead of id for multiple row
<!--
1- use class insteadd of id for multiple row, Make it text field.
2- Make it text field, to append the total calculated value
3- And also upadte it to readonly, beacause this field is for display the total calculated amount. -->
<td><input type="text" name="fiyat[]" readonly data-noaction="true" class="toplam mytext" /></td>
For multiple row, get the closest row (tr) field value for calculating and display
jQuery code.
$(document).ready(function(){
$('input[name^="fiyat"]').bind('keyup', function() {
//For multiple row, get the closest row (tr) field value for calculating and display
var closest = $(this).closest('tr');
//change .html to .val to add the value in text field.
closest.find('.toplam').val(closest.find('input[name^="fiyat"]').fonkTopla());
});
});
DEMO
I am using netbeans with chrome extension (netbeans connector) , i created a jsp page like this :
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Form Page</title>
</head>
<body>
<div align = "center">
<form >
<table border="0">
<tbody>
<tr>
<td>Name : </td>
<td><input type="text" name="Name" value="" /></td>
</tr>
<tr>
<td>Password : </td>
<td><input type="password" name="Password" value="" /></td>
</tr>
<tr>
<td>Age : </td>
<td><input type="text" name="Age" value="" /></td>
</tr>
<tr>
<td></td>
<td><input type="reset" value="Reset" style="float: right"/>
<input type="submit" value="Submit" style="float: right" onclick="onSubmit()" />
</td>
</tr>
</tbody>
</table>
</form>
</div>
<div align = "center">
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<script language = "javascript">
function onSubmit(){
var name = document.getElementsByName('Name')[0] ;
var password = document.getElementsByName('Password')[0] ;
var age = document.getElementsByName('Age')[0] ;
if(age.value >= 50){
alert('You\'re too old !');
}
var table = document.getElementsByTagName('table')[1] ;
var body = table.getElementsByTagName('tbody')[0] ;
var trNode = document.createElement('tr') ;
var thNameNode = document.createElement('td') ;
var nameTextNode = document.createTextNode(name.value.toString()) ;
thNameNode.appendChild(nameTextNode) ;
var thAgeNode = document.createElement('td') ;
var ageTextNode = document.createTextNode(age.value) ;
thAgeNode.appendChild(ageTextNode) ;
trNode.appendChild(thNameNode) ;
trNode.appendChild(thAgeNode) ;
body.appendChild(trNode) ;
}
</script>
</body>
the function onSubmit() is supposed to add a row in the table dynamically, but when i run on the browser the changes appear briefly and i am redirected again to original page , what is exactly the problem?
Form gets submitted on onSubmit function, you can prevent it by return false.
So below should work
function onSubmit(){
var name = document.getElementsByName('Name')[0] ;
var password = document.getElementsByName('Password')[0] ;
var age = document.getElementsByName('Age')[0] ;
if(age.value >= 50){
alert('You\'re too old !');
}
var table = document.getElementsByTagName('table')[1] ;
var body = table.getElementsByTagName('tbody')[0] ;
var trNode = document.createElement('tr') ;
var thNameNode = document.createElement('td') ;
var nameTextNode = document.createTextNode(name.value.toString()) ;
thNameNode.appendChild(nameTextNode) ;
var thAgeNode = document.createElement('td') ;
var ageTextNode = document.createTextNode(age.value) ;
thAgeNode.appendChild(ageTextNode) ;
trNode.appendChild(thNameNode) ;
trNode.appendChild(thAgeNode) ;
body.appendChild(trNode) ;
return false;
}
You have few options to achieve this.
Use type = 'button' instead of type= 'submit'
Use return false in click handler. Not to forget return in inline event binding. e.g. onclick='return onSubmit()'. Fiddle here
Use e.preventDefault() Fiddle here
I am trying to fill a table with random numbers and then have a user complete the totals. After entering the totals I wanted to check the answers, if the answer is correct I wanted to no longer allow input if the answer was wrong I wanted the cell highlighted and allow the user to try again.
The table is filling and incorrect answers are being identified however further attempts to modify the answers don't give any feedback. I am not sure why the input button can't be used multiple times I am guessing something needs to be cleared to accept another entry. I am just playing with JS so this is probably something very simple but I haven't been able to find a working solution.
Thanks
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Testing</title>
<link href='https://fonts.googleapis.com/css? family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,800,700,600,300' rel='stylesheet' type='text/css'/>
<script type="text/javascript">
var ran = new Array(4);
var count = 0;
function randomArray ( )
{
count = 0;
var max = 10;
var min = 5;
for ( var i = 0; i < ran.length; ++i)
{
ran[i] = Math.floor(Math.random()*(max - min + 1) + min);
}
iter = Math.floor(Math.random()*(4));
iter2 = Math.floor(Math.random()*(4));
}
function fillRandom(id)
{
document.getElementById(id).innerHTML = ran[count];
count++;
}
function check(id, id2, i, j)
{
var ans = document.getElementById(id).value.toString();
var soln = document.getElementById(id2);
//document.getElementById(id2).style.border = "thick red double";
if (ans != (ran[i] + ran[j]))
{
soln.style.border = "thick red double";
correct = false;
}
else
{
soln.innerHTML = (ran[i] + ran[j]);
correct = true;
}
}
</script>
</head>
<body>
<h1>Testing</h1>
<input type="submit" value="Get Questions" onclick="randomArray();fillRandom('num1');fillRandom('num2');fillRandom('num3');fillRandom('num4');"/>
<p>Try the following questions:</p>
<table id="data" border="thin black">
<tr>
<td> </td>
<td id="A">A</td>
<td id="B">B</td>
<td>Total</td>
</tr>
<tr>
<td id="C">C</td>
<td id="num1"> </td>
<td id="num2"> </td>
<td id="t12"><input id="total_1_2" type="text" /></td>
</tr>
<tr>
<td id="D">D</td>
<td id="num3"> </td>
<td id="num4"> </td>
<td id="t34"><input id="total_3_4" type="text" /></td>
</tr>
<tr>
<td>Total</td>
<td id="t13" ><input type="text" id="total_1_3"/></td>
<td id="t24"><input type="text" id="total_2_4"/></td>
<td id="t"><input type="text" id="total"/></td>
</tr>
</table>
<br/>
<input type="submit" value="Check Total" onclick="check('total_1_2', 't12', '0', '1');check('total_3_4', 't34', '2', '3');check('total_1_3', 't13', '0', '2');
check('total_2_4', 't24', '1', '3')">
</body>
</html>
function check(id, id2, i, j)
{
var ans ;
if(document.getElementById(id) !== null)
ans = document.getElementById(id).value;
else
ans = document.getElementById(id2).textContent;
var soln = document.getElementById(id2);
if (ans != (ran[i] + ran[j]))
{
soln.style.border = "thick red double";
correct = false;
}
else
{
soln.innerHTML = (ran[i] + ran[j]);
soln.style.border = "none";
correct = true;
}
}
http://jsfiddle.net/g6zhL/
When you correct an entry and click on “Check Total”, the code now turns the input element to content consisting of the user data, but it does not change the cell border. The border was set to thick red double, and nothing changes that. A minimal fix would be to edit that part of the if statement in the check function so that normal border is set: soln.style.border = "solid thin black";.
However, there is much else to be fixed in the design. Now if you enter several incorrect answers and fix one of them, then click on “Check Total”, you will see an error message in the console log. The reason is that the checking code tries to get the user data from input elements, even in the cell that now contains no input element. So you may need to modify the logic so that input elements are not removed or so that input elements that were removed are also removed from the set of elements to be checked.
I'm trying to make a simple converter like this one, but in JavaScript, where you enter an amount in tons and it displays a bunch of different numbers calculated from the input, sort of like this:
This is what I've tried:
<html>
<head>
<title>Calculator</title>
<script type="text/javascript">
function calculate(t){
var j = document.getElementById("output")
var treesSaved = t.tons.value * 17;
j.value = treesSaved;
}
</script>
</head>
<body>
<form>
<input type="text" placeholder="Tons" id="tons" />
<input type="button" value="Calculate" onclick="calculate(this.form)" />
<br />
<input type="text" id="output" value="Output" />
</form>
</body>
</html>
This works, to the extent that when you press the button, it calculates and displays the right number. However, it also seems to reset the form when I press the button, and I'm hoping to eliminate the need for the button altogether (so on every key press it recalculates).
Why is the form resetting, and how could I extend this to not need the button at all?
Here is the fiddle link for it:
Calculator
Use the below code to achieve what I think you want to :
<html>
<head>
<title>Calculator</title>
<script type="text/javascript">
function calculate(t){
var j = document.getElementById("output");
var rege = /^[0-9]*$/;
if ( rege.test(t.tons.value) ) {
var treesSaved = t.tons.value * 17;
j.value = treesSaved;
}
else
alert("Error in input");
}
</script>
</head>
<body>
<form>
<input type="text" placeholder="Tons" id="tons" onkeyup="calculate(this.form)"/>
<input type="button" value="Calculate" onclick="calculate(this.form)" />
<br />
<input type="text" id="output" value="Output" />
</form>
</body>
</html>
Please check this FIDDLE.
All you need to adding attributes data-formula to your table cells.
HTML
<table border="1">
<tr>
<td>
<input type="text" id="initial-val" />
</td>
<td>card board</td>
<td>recycled</td>
<td>reusable</td>
</tr>
<tr>
<td>lovely trees</td>
<td data-formula='val*5'></td>
<td data-formula='val+10'></td>
<td data-formula='val/2'></td>
</tr>
<tr>
<td>what is acres</td>
<td data-formula='val*2'></td>
<td data-formula='val*(1+1)'></td>
<td data-formula='val*(10/5)'></td>
</tr>
</table>
JAVASCRIPT
$(function () {
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
var $input = $('#initial-val'),
$cells = $('td[data-formula]');
$input.on('keyup', function () {
var val = $input.val();
if (isNumber(val)) {
$.each($cells, function () {
var $thisCell = $(this);
$thisCell.text(
eval($thisCell.attr('data-formula').replace('val', val.toString()))
)
});
} else {
$cells.text('ERROR')
}
});
});
You'll need:
a drop down option that allows the user to select what type of calculation they want to do and then display an input field OR multiple input fields
an input field for user input
a submit button with a onclick() event which passes your input into your calculation
(you may want to do some validation on this so they can only enter numbers)
validation examples
your Javascript file that takes the input from your box on submit and performs your calculation
display the information back to user... something like innerHtml to an element you've selected or:
var output = document.getelementbyid("your outputbox")
output.value = "";
output.value = "your calculated value variable";
Here is a tutorial for grabbing user input.
Assuming your calculations are all linear, I would suggest that you create an array of the coefficients and then just loop that array to do the calculation and print it out. Something like this:
HTML:
<table>
<tr>
<th></th>
<th>Recycled Cardboard</th>
<th>Re-usable Cardboard</th>
</tr>
<tr>
<th>Trees Saved</th>
<td></td><td></td>
</tr>
<tr>
<th>Acres Saved</th>
<td></td><td></td>
</tr>
<tr>
<th>Energy (in KW)</th>
<td></td><td></td>
</tr>
<tr>
<th>Water (in Gallons)</th>
<td></td><td></td>
</tr>
<tr>
<th>Landfill (Cubic Yards)</th>
<td></td><td></td>
</tr>
<tr>
<th>Air Pollution (in Lbs)</th>
<td></td><td></td>
</tr>
</table>
Javascript:
function showStats(cardboardTons) {
var elements = $("td");
var coeffs = [17, 34, 0.025, 0.5, 4100, 8200, 7000, 14000, 3, 6, 60, 120];
for(var i=0;i<coeffs.length;i++)
elemnts.eq(i).html(cardboardTons * coeffs);
}
Once you get input from the user, pass it into the showStats function as a number and it will go through all of the cells in the table and calculate the proper number to go in it.