Javascript Functions for Form are not Displaying with textContent - javascript

In my current code, I have a form that takes in 4 input quantities. Once inputted, the user will click the purchase button and the total counts of: total items, subtotal, sales tax, total and final discount amount will display based on what the user previously inputted.
My current issue is that nothing seems to print. Not even my error checking print.
So far all that displays is the current "0" values for each value for the shopping cart.
Please help me understand where my issues lie.
I have some concern that the getElementsByClassId may be causing my problem too for the class inside the () for it. Not completely sure where to start.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- Set the viewport so this responsive site displays correctly on mobile devices -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Page title </title>
<!-- Include bootstrap CSS -->
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<!-- Include jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
thead { background-color: #333; color: #fff; font-weight: bold; }
.items, #nitems, #subtotal, #tax, #total, #final {text-align: right; width: 100px; }
#checkout { margin-bottom: 45px; width: 200px; height: 50px; font-weight: bold; }
#errors { padding-bottom: 200px; clear: both; font-weight: bold; clear: both; font-size: 20px;
color: blue;
}
</style>
</head>
<body class='container'>
<form name="testForm">
<div class='row'>
<div class='col-md-8'>
<h2>Sam's Online Shop</h2>
<h3>15% discount on all online sales </h3>
<h3>Our World Famous Chocolates Now Available Online </h3>
<table class='table'>
<thead>
<tr>
<th>Product</th><th>Unit cost</th><th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td id="ch-1-label">Milk Chocolate</td>
<td id="ch-1-cost">7.48</td>
<td><input size=3 name="milkchoc" id="ch-1-qnt" class="form-control items" value="0"></td>
</tr>
<tr>
<td id="ch-2-label">Assorted Fine Chocolates</td>
<td id="ch-2-cost">9.98</td>
<td><input size=3 name="foil" id="ch-2-qnt" class="form-control items" value="0"></td>
</tr>
<tr>
<td id="ch-3-label">Assorted Milk & Dark Chocolates</td>
<td id="ch-3-cost">12.98</td>
<td><input size=3 name="dc" id="ch-3-qnt" class="form-control items" value="0"></td>
</tr>
<tr>
<td id="ch-4-label">Assorted Dessert Truffles</td>
<td id="ch-4-cost">15.98</td>
<td><input size=3 name="dt" id="ch-4-qnt" class="form-control items" value="0"></td>
</tr>
</tbody>
</table>
</div>
</div>
<div class='row'>
<div class='col-md-4'>
<h3>Shopping Cart </h3>
<table class='table'>
<tr>
<td>Total Items</td>
<td><span id="nitems" >0</td>
</tr>
<tr>
<td>Subtotal</td>
<td><span id="subtotal" >0</td>
</tr>
<tr>
<td>5% Sales tax</td>
<td><span id="tax" >0</td>
</tr>
<tr>
<td>Total</td>
<td><span id="total" >0</td>
</tr>
<tr>
<td>Final amount (with 15% discount)</td>
<td><span id="final" >0</td>
</tr>
</table>
<p><input type="button" value="Purchase" id="checkout" class="form-control btn btn-primary" /></p>
<p><span id='errors'></span></p>
</div>
</div>
JAVASCRIPT CODE AT BOTTOM OF HTML CODE
<script>
// Include Javascript code here
document.getElementById('Purchase').onclick = function() {
var milk = document.getElementById('ch-1-qnt').value;
var fine = document.getElementById('ch-2-qnt').value;
var both = document.getElementById('ch-3-qnt').value;
var truff = document.getElementById('ch-4-qnt').value;
//Check for errors
var errors = checkErrors();
//Display the errors
if (errors.length > 0)
//displayErrors(errors);
checkErrors();
}
else {
// Display function for total count of items purchased
displayitems();
// Return subTotal function that totals the initial cost for all
var subTotal = Sub(milk, fine, both, truff);
document.getElementByID('subtotal').textContent = subTotal;
//Return Tax function totals
var salesTax = Tax(subTotal);
document.getElementById('tax').textContent = salesTax;
// Return the total cost for Subtotal cost and salesTax cost
var Total = displayTotal(subTotal, salesTax);
document.getElementById('total').textContent = Total;
// Display discount pricing
var DiscountTotal = Total * .15;
document.getElementById('final').textContent = DiscountTotal;
}
//Returns an array of error messages
function checkErrors() {
var list = [];
for (var j = 1; j<4; j++){
if (document.getElementById('ch-' + j + '-qnt')).value <0 ) {
document.getElementById('errors').innerHTML = list;
}
}
}
// Display total item counts
function displayItems() {
var total = 0;
var input = document.getElementsByClassId('form-control items');
for (var i=0; i<input.length; i++){
total += parseFloat(input[i].value);
}
document.getElementById('nitems').textContent = total;
}
//Function to return the subtotal for all 4 inputs
function Sub(milk, fine, both, truff) {
var total1, total2, total3, total4 = 0;
var Final = 0;
var costMilk = 7.48;
var costFine = 9.98;
var costBoth = 12.98;
var costTruff = 15.98;
total1 = costMilk * milk;
total2 = costFine *fine;
total3 = costBoth * both;
total4 = costTruff * truff;
Final = total1 + total2 + total3 + total4;
return Final;
}
// Returns tax total
function Tax(subTotal) {
subTotal = Sub(milk, fine, both, truff);
var Tax = subTotal * .05;
return Tax;
}
function displayTotal(Tax, Sub){
return Tax * Sub;
}
};
</script>
</body>
</html>

You have many errors on your scripts, the list of errors are
document.getElementById('Purchase').onclick // using wrong id Purchase but checkout
if (errors.length > 0) //forgot closing brace {, but if (errors.length > 0){
displayitems(); //wrong function calling, but displayItems()
document.getElementsByClassId('form-control items'); //should be document.getElementsByClassName
(document.getElementById('ch-' + j + '-qnt').value) <0 ) //extra parenthesis ) after value, but (document.getElementById('ch-' + j + '-qnt').value <0 )
document.getElementById('checkout').onclick = function() {
var milk = document.getElementById('ch-1-qnt').value;
var fine = document.getElementById('ch-2-qnt').value;
var both = document.getElementById('ch-3-qnt').value;
var truff = document.getElementById('ch-4-qnt').value;
//Check for errors
var errors = checkErrors();
//Display the errors
if (errors.length > 0) {
//displayErrors(errors);
checkErrors();
}else {
// Display function for total count of items purchased
displayItems();
// Return subTotal function that totals the initial cost for all
var subTotal = Sub(milk, fine, both, truff);
document.getElementById('subtotal').textContent = subTotal;
//Return Tax function totals
var salesTax = Tax(subTotal);
document.getElementById('tax').textContent = salesTax;
// Return the total cost for Subtotal cost and salesTax cost
var Total = displayTotal(subTotal, salesTax);
document.getElementById('total').textContent = Total;
// Display discount pricing
var DiscountTotal = Total * .15;
document.getElementById('final').textContent = DiscountTotal;
}
//Returns an array of error messages
function checkErrors() {
var list = [];
for (var j = 1; j<4; j++){
if (document.getElementById('ch-' + j + '-qnt').value <0 ) {
document.getElementById('errors').innerHTML = list;
}
}
return list;
}
// Display total item counts
function displayItems() {
var total = 0;
var input = document.getElementsByClassName('form-control items');
for (var i=0; i<input.length; i++){
total += parseFloat(input[i].value);
}
document.getElementById('nitems').textContent = total;
}
//Function to return the subtotal for all 4 inputs
function Sub(milk, fine, both, truff) {
var total1, total2, total3, total4 = 0;
var Final = 0;
var costMilk = 7.48;
var costFine = 9.98;
var costBoth = 12.98;
var costTruff = 15.98;
total1 = costMilk * milk;
total2 = costFine *fine;
total3 = costBoth * both;
total4 = costTruff * truff;
Final = total1 + total2 + total3 + total4;
return Final;
}
// Returns tax total
function Tax(subTotal) {
subTotal = Sub(milk, fine, both, truff);
var Tax = subTotal * .05;
return Tax;
}
function displayTotal(Tax, Sub){
return Tax * Sub;
}
};
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<!-- Include jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
thead { background-color: #333; color: #fff; font-weight: bold; }
.items, #nitems, #subtotal, #tax, #total, #final {text-align: right; width: 100px; }
#checkout { margin-bottom: 45px; width: 200px; height: 50px; font-weight: bold; }
#errors { padding-bottom: 200px; clear: both; font-weight: bold; clear: both; font-size: 20px;
color: blue;
}
</style>
</head>
<body class='container'>
<form name="testForm">
<div class='row'>
<div class='col-md-8'>
<h2>Sam's Online Shop</h2>
<h3>15% discount on all online sales </h3>
<h3>Our World Famous Chocolates Now Available Online </h3>
<table class='table'>
<thead>
<tr>
<th>Product</th><th>Unit cost</th><th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td id="ch-1-label">Milk Chocolate</td>
<td id="ch-1-cost">7.48</td>
<td><input size=3 name="milkchoc" id="ch-1-qnt" class="form-control items" value="0"></td>
</tr>
<tr>
<td id="ch-2-label">Assorted Fine Chocolates</td>
<td id="ch-2-cost">9.98</td>
<td><input size=3 name="foil" id="ch-2-qnt" class="form-control items" value="0"></td>
</tr>
<tr>
<td id="ch-3-label">Assorted Milk & Dark Chocolates</td>
<td id="ch-3-cost">12.98</td>
<td><input size=3 name="dc" id="ch-3-qnt" class="form-control items" value="0"></td>
</tr>
<tr>
<td id="ch-4-label">Assorted Dessert Truffles</td>
<td id="ch-4-cost">15.98</td>
<td><input size=3 name="dt" id="ch-4-qnt" class="form-control items" value="0"></td>
</tr>
</tbody>
</table>
</div>
</div>
<div class='row'>
<div class='col-md-4'>
<h3>Shopping Cart </h3>
<table class='table'>
<tr>
<td>Total Items</td>
<td><span id="nitems" >0</td>
</tr>
<tr>
<td>Subtotal</td>
<td><span id="subtotal" >0</td>
</tr>
<tr>
<td>5% Sales tax</td>
<td><span id="tax" >0</td>
</tr>
<tr>
<td>Total</td>
<td><span id="total" >0</td>
</tr>
<tr>
<td>Final amount (with 15% discount)</td>
<td><span id="final" >0</td>
</tr>
</table>
<p><input type="button" value="Purchase" id="checkout" class="form-control btn btn-primary" /></p>
<p><span id='errors'></span></p>
</div>
</div>

Related

Is there anyway to show always rows modified in a FooTable

The system is made with php, mysql, javascript, jquery and what it does is show a list of products and the user chooses the amount and shows a total.
I want to make a function that when the user modifies the quantity of a row, the row is always displayed in the Table, no matter if they search for other products or change the page of the table
This is the code
<table class="table-striped footable-res footable metro-blue" data-page-size="36" data-filter="#filter" style="color: #666;" data-filter-exact-match="false" id="tb">
<thead>
<th width="5%">°</th>
<th width="40%">Producto</th>
<th width="15%">Precio</th>
<th width="15%">Cantidad</th>
<th width="15%">Total</th>
<tr></tr>
</thead>
<tbody>
<td colspan=5 data-value='Nombre de categoria'><b>Nombre de categoria</b></td><tr></tr>";
<td>Contador 1</td>";
<input type='text' name='seleccion1' value='IDPRODUCTO' style='visibility: hidden !important; height: 0 !important; width: 0 !important; padding: 0 !important;'>";
<td data-value='NOMBREPRODUCTO CATEGORIAID CATEGORIANOMBRE' data-type='text'>"PRODUCTONOMBRE"</td>";
<td><input type='text' class='precio' name='precioIDPRODUCTO' id='precio' value='PR' style='color: black; background: transparent; border: 0; text-align: center;' readonly></td>";
<td><input type='text' class='cantidad' name='cantidadIDPRODUCTO' id='cantidad' placeholder='0' placeholder='0' style='color: black;'></td>";
<td><input type='text' class='total' name='totalIDPRODUCTO' id='total' value='0' value='0' style='color: black;'></td>";
<tr></tr>
}
}
if (CONTADOR==0){
<td colspan='3'>No se han agregado productos aún.</td>";
}
echo "<input type='text' name='cod_bod' value='".$sel_bodega."' style='visibility: hidden !important; height: 0 !important; width: 0 !important; padding: 0 !important;'>";
}
?>
</tbody>
<tfoot>
<style>
.footable > tfoot > tr > th, .footable > tfoot > tr > td{ color: black; }
input[type=text]{ color: black; }
</style>
<td colspan="4" align="right">Subtotal</td>
<td><input type="text" class="subtotal" name="subtotal" id="subtotal" readonly placeholder="0"></td>
<tr></tr>
<td colspan="4" align="right">Descuento %<input type="text" id="discount" name="discount" class="discount" style="color: black; background: transparent; border: 0; text-align: center; width: 20px;" value="0"></td>
<td><input type="text" class="descuento" class="descuento" name="descuento" id="descuento" readonly placeholder="0"></td>
<tr></tr>
<td colspan="4" align="right">Total</td>
<td><input type="number" pattern="[0-9]{2}" min="50000" max="2000000" class="totales" id="totales" name="totales" readonly placeholder="0" ></td>
<tr>
<td colspan="5">
<div class="pagination pagination-centered"></div>
</td>
</tr>
</tfoot>
</table>
<script>
//data-toggle="true"
document.getElementById("tb").addEventListener("input", function(e) {
const parent = e.target.closest("tr");
const precio = parent.querySelector('[class=precio]').value;
const cantidad = parent.querySelector('[class=cantidad]').value;
const total = precio * cantidad;
parent.querySelector('[class=total]').value = total;
document.querySelector('[class=subtotal]').value = subtotal();
document.querySelector('[class=discount]').value = discount();
document.querySelector('[class=descuento]').value = dscto();
document.querySelector('[class=totales]').value = totalfinal();
});
function subtotal(){
var subtotal = 0;
for(var x=0;x<document.querySelectorAll(".total").length;x++){
subtotal += Number(document.querySelectorAll(".total")[x].value);
}
return subtotal;
}
function discount(){
var subtotal = Number(document.getElementById("subtotal").value);
var discount = 0;
if(subtotal > 150000 && subtotal < 299999){
discount = 3;
}
if(subtotal > 300000 && subtotal < 449999){
discount = 4;
}
if(subtotal > 450000){
discount = 5;
}
return discount;
}
function dscto(){
var subtotal = Number(document.getElementById("subtotal").value);
var descuento = 0;
if(subtotal > 150000 && subtotal < 299999){
descuento = subtotal * 0.03;
}
if(subtotal > 300000 && subtotal < 449999){
descuento = subtotal * 0.04;
}
if(subtotal > 450000){
descuento = subtotal * 0.05;
}
return descuento;
}
function totalfinal(){
var subtotal2 = Number(document.getElementById("subtotal").value);
var descuento2 = Number(document.getElementById("descuento").value);
var totales = subtotal2 - descuento2;
return totales;
}

My submited table does not show on the browser

I have a scoreboard where the user can enter the score and when the user presses the "Submit" button it will show a table that will contain the information that the user has entered. But when I try it in the browser, my table doesn't show the information that was entered in the previous form, it only show the table heading. Let me explain like below:
var testScore = {
name: "",
math: 0,
physical: 0,
chemistry: 0,
avg: 0
};
var i = 1;
// This is the table will show after submited
function score_table() {
document.getElementById("divTable").style.display = "block";
// Gathering the data
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 = (parseFloat(testScore.math) + parseFloat(testScore.physics) + parseFloat(testScore.chemistry)) / 3;
// How to get this average score has the form like 8,33 or 6,69, I need //help
document.getElementById("name").value = "";
document.getElementById("math").value = "";
document.getElementById("physics").value = "";
document.getElementById("chemical").value = "";
// Add the information but why it does not work
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++;
}
#divTable {
display: none;
width: 100%;
}
#tableScore th:nth-child(6),
#tableScore td:nth-child(6) {
display: none;
}
<script src="js/script.js"></script>
<h1 align="center">Class Marksheet</h1>
<!--This is the first table when user access the browser-->
<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>
<!--This button will show the second table below-->
<button type="submit" onclick="score_table()">Submit</button>
</td>
</table>
<div id="divTable">
<!--This table only show when user click on the "Submit" button and it contains
all the information that submitted. But I try on browser and it is not show the information.
-->
<table id="tableScore" border="2">
<th>No</th>
<th>Name</th>
<th>Math</th>
<th>Physics</th>
<th>Chemistry</th>
<th>Average score</th>
</table>
<button onclick="showAvg()">Show the average score</button>
<button onclick="showBest()">Best student</button>
</div>
In js code you have used innerHtml instead of innerHTML.
Updated code:
var testScore = {
name: "",
math: 0,
physical: 0,
chemistry: 0,
avg: 0
};
var i = 1;
// This is the table will show after submited
function score_table() {
document.getElementById("divTable").style.display = "block";
// Gathering the data
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 = (parseFloat(testScore.math) + parseFloat(testScore.physics) + parseFloat(testScore.chemistry)) / 3;
// How to get this average score has the form like 8,33 or 6,69, I need //help
document.getElementById("name").value = "";
document.getElementById("math").value = "";
document.getElementById("physics").value = "";
document.getElementById("chemical").value = "";
// Add the information but why it does not work
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++;
}
#import url('https://fonts.googleapis.com/css2?family=Bree+Serif&family=Caveat:wght#400;700&family=Lobster&family=Monoton&family=Open+Sans:ital,wght#0,400;0,700;1,400;1,700&family=Playfair+Display+SC:ital,wght#0,400;0,700;1,700&family=Playfair+Display:ital,wght#0,400;0,700;1,700&family=Roboto:ital,wght#0,400;0,700;1,400;1,700&family=Source+Sans+Pro:ital,wght#0,400;0,700;1,700&family=Work+Sans:ital,wght#0,400;0,700;1,700&display=swap');
#divTable {
display: none;
width: 100%;
}
#tableScore th:nth-child(6),
#tableScore td:nth-child(6) {
display: none;
}
<!DOCTYPE html>
<html>
<head> </head>
<body>
<script src="js/script.js"></script>
<h1 align="center">Class Marksheet</h1>
<!--This is the first table when user access the browser-->
<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>
<!--This button will show the second table below-->
<button type="submit" onclick="score_table()">Submit</button>
</td>
</table>
<div id="divTable">
<!--This table only show when user click on the "Submit" button and it contains
all the information that submitted. But I try on browser and it is not show the information.
-->
<table id="tableScore" border="2">
<th>No</th>
<th>Name</th>
<th>Math</th>
<th>Physics</th>
<th>Chemistry</th>
<th>Average score</th>
</table>
<button onclick="showAvg()">Show the average score</button>
<button onclick="showBest()">Best student</button>
</div>
</body>
</html>
When you use insertCell you need to use innerHTML or appendChild instead of the non-existent innerHtml
Also you do not need to have any integer in insertCell/Row
Also your HTML was invalid
number.appendChild(document.createTextNode(i));
name.appendChild(document.createTextNode(testScore.name));
math.appendChild(document.createTextNode(testScore.math));
physics.appendChild(document.createTextNode(testScore.physics));
chemistry.appendChild(document.createTextNode(testScore.chemistry));
avg.appendChild(document.createTextNode(testScore.avg));
var testScore = {
name: "",
math: 0,
physical: 0,
chemistry: 0,
avg: 0
};
var i = 1;
// This is the table will show after submited
function score_table() {
document.getElementById("divTable").style.display = "block";
// Gathering the data
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;
// How to get this average score has the form like 8,33 or 6,69, I need //help
document.getElementById("name").value = "";
document.getElementById("math").value = "";
document.getElementById("physics").value = "";
document.getElementById("chemical").value = "";
// Add the information but why it does not work
var table = document.querySelector("#tableScore tbody");
var row = table.insertRow();
var number = row.insertCell();
var name = row.insertCell();
var math = row.insertCell();
var physics = row.insertCell();
var chemistry = row.insertCell();
var avg = row.insertCell();
number.appendChild(document.createTextNode(i));
name.appendChild(document.createTextNode(testScore.name));
math.appendChild(document.createTextNode(testScore.math));
physics.appendChild(document.createTextNode(testScore.physics));
chemistry.appendChild(document.createTextNode(testScore.chemistry));
avg.innerHTML = testScore.avg; // alternative to appendChild
i++;
}
#divTable {
display: none;
width: 100%;
}
#tableScore th:nth-child(6),
#tableScore td:nth-child(6) {
display: none;
}
<script src="js/script.js"></script>
<h1 align="center">Class Marksheet</h1>
<!--This is the first table when user access the browser-->
<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>
<!--This button will show the second table below-->
<button type="submit" onclick="score_table()">Submit</button>
</td>
</table>
<div id="divTable">
<!--This table only show when user click on the "Submit" button and it contains
all the information that submitted. But I try on browser and it is not show the information.
-->
<table border="2" id="tableScore">
<thead>
<th>No</th>
<th>Name</th>
<th>Math</th>
<th>Physics</th>
<th>Chemistry</th>
<th>Average score</th>
</thead>
<tbody>
</tbody>
</table>
<button onclick="showAvg()">Show the average score</button>
<button onclick="showBest()">Best student</button>
</div>
You have some misspelled variables but you can also minimize your output with only one global innerHTML like in my example below:
var testScore = {
name: "",
math: 0,
physical: 0,
chemistry: 0,
avg: 0
};
var i = 1;
// This is the table will show after submited
function score_table() {
document.getElementById("divTable").style.display = "block";
// Gathering the data
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 = (parseFloat(testScore.math) + parseFloat(testScore.physics) + parseFloat(testScore.chemistry)) / 3;
// How to get this average score has the form like 8,33 or 6,69, I need //help
document.getElementById("name").value = "";
document.getElementById("math").value = "";
document.getElementById("physics").value = "";
document.getElementById("chemical").value = "";
//MINIMIZED VERSION
document.getElementById("tableScore").innerHTML +=
"<td>" + i + "</td>" +
"<td>" + testScore.name + "</td>" +
"<td>" + testScore.math + "</td>" +
"<td>" + testScore.physical + "</td>" +
"<td>" + testScore.chemistry + "</td>" +
"<td>" + testScore.avg + "</td>";
i++;
}
#divTable {
display: none;
width: 100%;
}
#tableScore th:nth-child(6),
#tableScore td:nth-child(6) {
display: none;
}
<script src="js/script.js"></script>
<h1 align="center">Class Marksheet</h1>
<!--This is the first table when user access the browser-->
<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>
<!--This button will show the second table below-->
<button type="submit" onclick="score_table()">Submit</button>
</td>
</table>
<div id="divTable">
<!--This table only show when user click on the "Submit" button and it contains
all the information that submitted. But I try on browser and it is not show the information.
-->
<table id="tableScore" border="2">
<th>No</th>
<th>Name</th>
<th>Math</th>
<th>Physics</th>
<th>Chemistry</th>
<th>Average score</th>
</table>
<button onclick="showAvg()">Show the average score</button>
<button onclick="showBest()">Best student</button>
</div>

Alert to stop duplicate data

I am trying to add an alert to notify the user that data has already been entered. I want to apply this to the flight number only. So that when a user types in an already typed flight number and saves it into the array it will pop up a message telling them that it has already been posted.
<html>
<head>
<title>Member Info</title>
<style>
table, th, td {
border: 1px solid black;
text-align: center;
border-collapse: collapse;
}
</style>
<script type="text/javascript">
var FlightNumber=new Array();
var Miles=new Array();
function insert(){
var FlightNumberValue = document.getElementById('FlightNumber').value;
var MilesValue = document.getElementById('Miles').value;
FlightNumber[FlightNumber.length]=FlightNumberValue;
Miles[Miles.length]=MilesValue;
}
function showFlightNumber() {
var content="<b></b><br>";
for(var i = 0; i < FlightNumber.length; i++) {
content +=FlightNumber[i]+"<br>";
}
document.getElementById('display').innerHTML = content;
}
function showMiles() {
var content="<b></b><br>";
for(var i = 0; i < Miles.length; i++) {
content +=Miles[i]+"<br>";
}
document.getElementById('display2').innerHTML = content;
// new code
var total=0;
for(var i = 0; i < Miles.length; i++) {
total += Number.parseInt(Miles[i]);
}
document.getElementById('total-miles').innerHTML = total;
}
</script>
</head>
<body>
<form id="form">
<h1>Find out what Flight Class Member you are!</h1>
<p>To use, please input the flight number and number of miles. Press save and then show. To enter more than one press "Enter More" button and repeat steps.<p>
<br>
<label for="FlightNumber">Flight Number</label> <input id="FlightNumber" type="text" />
<br>
<label for="Miles">Miles</label><input id="Miles" type="text" />
<br>
<br>
<input type="button" value="Save" onclick="insert();">
<input type="button" value="Show flight number" onclick="showFlightNumber();">
<input type="button" value="Show miles" onclick="showMiles();">
<input type= "reset" value="Enter More" />
<hr>
</form>
<table style="width:100%">
<tr>
<th>Flight Number</th>
<th>Miles</th>
</tr>
<tr>
<td><div id="display">
</div></td>
<td><div id="display2">
</div></td>
</tr>
<td>Total Miles:</td>
<td id="total-miles"></td>
</table>
<br><br>
<table id="MemberTable" style="width:100%", border="1px solid black">
<tr>
<td>Bronze Member</td>
<td><10000 miles flown</td>
</tr>
<tr>
<td>Silver Member</td>
<td><25000 miles flown</td>
</tr>
<tr>
<td>Gold Member</td>
<td>>25000 miles flown</td>
</tr>
</table>
</body>
</html>
I am also trying to highlight the member table to show which group they are in based on total miles. I would like for the color of the highlight to match the member level. Something kind of like this:
<style>
.bronze {
background: rgb(80.4, 49.8, 19.6);
}
.silver {
background: silver
}
.gold {
background: gold
}
</style>
<script>
function highlightWeightClass(total-miles) {
var rows = document.getElementById("MemberTable").rows;
rows[0].className = total-miles< 10000 ? "bronze" : "";
rows[1].className = total-miles >= 10000 && total-miles < 25000 ? "silver" : "";
rows[2].className = total-miles >= 25000 ? "gold" : "";
</script>
For checking if an Array contains on Object, use this:
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
For highlighting the member table: add an event listener for document.getElementById("Miles")'s keyup and execute your function then.
<html>
<head>
<title>Member Info</title>
<style>
table, th, td {
border: 1px solid black;
text-align: center;
border-collapse: collapse;
}
.bronze {
background: rgb(80.4, 49.8, 19.6);
}
.silver {
background: silver
}
.gold {
background: gold
}
</style>
<script>
Array.prototype.contains = function(obj) {//function to check if an Array contains an object
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
function highlightWeightClass(totalmiles) {
var rows = document.getElementById("MemberTable").rows;
rows[0].className = totalmiles< 10000 ? "bronze" : "";
rows[1].className = totalmiles >= 10000 && totalmiles < 25000 ? "silver" : "";
rows[2].className = totalmiles >= 25000 ? "gold" : "";
}
</script>
<script type="text/javascript">
var FlightNumber=new Array();
var Miles=new Array();
function insert(){
var FlightNumberValue = document.getElementById('FlightNumber').value;
if(!FlightNumber.contains(FlightNumberValue)){
var MilesValue = document.getElementById('Miles').value;
FlightNumber[FlightNumber.length]=FlightNumberValue;
Miles[Miles.length]=MilesValue;
} else {
alert("You have already entered this flight number.");
}
}
function showFlightNumber() {
var content="<b></b><br>";
for(var i = 0; i < FlightNumber.length; i++) {
content +=FlightNumber[i]+"<br>";
}
document.getElementById('display').innerHTML = content;
}
function showMiles() {
var content="<b></b><br>";
for(var i = 0; i < Miles.length; i++) {
content +=Miles[i]+"<br>";
}
document.getElementById('display2').innerHTML = content;
// new code
var total=0;
for(var i = 0; i < Miles.length; i++) {
total += Number.parseInt(Miles[i]);
}
document.getElementById('total-miles').innerHTML = total;
}
window.onload = function(){
document.getElementById("Miles").addEventListener("keyup", function(event){
highlightWeightClass(document.getElementById("Miles").value);
});
}
</script>
</head>
<body>
<form id="form">
<h1>Find out what Flight Class Member you are!</h1>
<p>To use, please input the flight number and number of miles. Press save and then show. To enter more than one press "Enter More" button and repeat steps.<p>
<br>
<label for="FlightNumber">Flight Number</label> <input id="FlightNumber" type="text" />
<br>
<label for="Miles">Miles</label><input id="Miles" type="text" />
<br>
<br>
<input type="button" value="Save" onclick="insert();">
<input type="button" value="Show flight number" onclick="showFlightNumber();">
<input type="button" value="Show miles" onclick="showMiles();">
<input type= "reset" value="Enter More" />
<hr>
</form>
<table style="width:100%">
<tr>
<th>Flight Number</th>
<th>Miles</th>
</tr>
<tr>
<td><div id="display">
</div></td>
<td><div id="display2">
</div></td>
</tr>
<td>Total Miles:</td>
<td id="total-miles"></td>
</table>
<br><br>
<table id="MemberTable" style="width:100%", border="1px solid black">
<tr>
<td>Bronze Member</td>
<td><10000 miles flown</td>
</tr>
<tr>
<td>Silver Member</td>
<td><25000 miles flown</td>
</tr>
<tr>
<td>Gold Member</td>
<td>>25000 miles flown</td>
</tr>
</table>
</body>
</html>

Parsing input without requiring button press with Javascript

I am currently looking for a solution to add some user-typed numbers instantly/automatically without having to click on any button. For now, I have a table asking the user for the numbers and displaying the result after the user clicked on the "Total" button. I would like to get rid of that button and that the "Total" row of the table automatically refresh to the new total, every time the user changes a value.
<!DOCTYPE html>
<html>
<head>
<title>Table</title>
<style>
body {
width: 100%;
height: 650px;
}
#rent, #food, #entertainment, #transportation, #total {
height: 30px;
font-size: 14pt;
}
</style>
</head>
<body>
<center>
<h1></h1>
<script type="text/javascript">
function CalcTotal() {
var total = 0;
var rent = +document.getElementById("rent").value;
var food = +document.getElementById("food").value;
var entertainment = +document.getElementById("entertainment").value;
var transportation = +document.getElementById("transportation").value;
var total = rent + food + entertainment + transportation;
document.getElementById("total").innerHTML = total;
}
</script>
<table border="1">
<tr>
<th>A</th>
<th>B</th>
</tr>
<tr>
<td>Rent</td><td><input type="text" id="rent"></td>
</tr>
<tr>
<td>Food</td><td><input type="text" id="food"></td>
</tr>
<tr>
<td>Entertainment</td><td><input type="text" id="entertainment"></td>
</tr>
<tr>
<td>Transportation</td><td><input type="text" id="transportation"> </td>
</tr>
<tr>
<td>Total</td><td><div id="total"></div></td>
</tr>
</table>
<input type="submit" value="Total" onclick="CalcTotal()" id="total">
</center>
</body>
</html>
Add a keyup listener to every input field:
function CalcTotal() {
var total = 0;
var rent = +document.getElementById("rent").value;
var food = +document.getElementById("food").value;
var entertainment = +document.getElementById("entertainment").value;
var transportation = +document.getElementById("transportation").value;
var total = rent + food + entertainment + transportation;
document.getElementById("total").innerHTML = total;
}
document.querySelectorAll('input[type="text"]')
.forEach(input => input.addEventListener('keyup', CalcTotal));
body {
width: 100%;
height: 250px;
}
#rent,
#food,
#entertainment,
#transportation,
#total {
height: 30px;
font-size: 14pt;
}
<table border="1">
<tr>
<th>A</th>
<th>B</th>
</tr>
<tr>
<td>Rent</td>
<td><input type="text" id="rent"></td>
</tr>
<tr>
<td>Food</td>
<td><input type="text" id="food"></td>
</tr>
<tr>
<td>Entertainment</td>
<td><input type="text" id="entertainment"></td>
</tr>
<tr>
<td>Transportation</td>
<td><input type="text" id="transportation"> </td>
</tr>
<tr>
<td>Total</td>
<td>
<div id="total"></div>
</td>
</tr>
</table>
<input type="submit" value="Total" onclick="CalcTotal()" id="total">
Note that NodeList.forEach is somewhat new - if you have to support old browsers, you'll have to use a polyfill, or iterate over the inputs some other way instead. For example:
Array.prototype.forEach.call(
document.querySelectorAll('input[type="text"]'),
input => input.addEventListener('keyup', CalcTotal)
);

add dynamic input field with unique id for counting

I am working on a code to calculate the total price of services.
Now if I add the hours (like 2) and add the price per hour (like 20) the code has to calculate the price that will become the subtotal. After that It calculate the "BTW" (tax) and add it to the subtotal for the total price.
What I would like is to add dynamic new input fields with a unique id so the code can calculate multiple services. So for each service you've got a total amount which all combined will be the subtotal. My code for now:
HTML
<table class="table-responsive table" id="table-diensten">
<thead>
<tr>
<th>Time</th>
<th>Service</th>
<th>amount</th>
<th>total</th>
<th>BTW</th>
</tr>
</thead>
<tbody class="table-body">
<tr class="table-row">
<td><input type="text" class="form-control" placeholder="time (in hours)" id="time" onchange="totalofferte()"></td>
<td><input type="text" class="form-control" placeholder="service"></td>
<td><input type="text" class="form-control" placeholder="Cost (per hour)" id="cost" onchange="totalofferte()"></td>
<td>€ <span id="total">0,00</span></td>
<td>21%</td>
</tr>
</tbody>
<tfoot>
<tr>
<td> </td>
<td> </td>
<td><strong>Subtotaal</strong></td>
<td>€ <span id="subtotal">0,00</span></td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td>21% BTW</td>
<td>€ <span id="costbtw">0,00</span></td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td class="table-total"><span class="total">Totaal</span></td>
<td class="table-total"><span class="total">€ <span id="totalofferte">0,00</span></span></td>
<td> </td>
</tr>
</tfoot>
</table>
<a href="#table-diensten" class="add-tablerow btn btn-default" >add new service</a>
JS
<script type="text/javascript">
function totalofferte() {
var cost = document.getElementById('cost').value;
var time = document.getElementById('time').value;
if (cost > 0 && time > 0) {
var total = cost * time;
if (total > 0) {
document.getElementById('total').innerHTML = total;
var subtotal = total;
if (subtotal > 0) {
document.getElementById('subtotal').innerHTML = subtotal;
var costbtw = subtotal / 100 * 21;
document.getElementById('costbtw').innerHTML = costbtw;
var totalofferte = subtotal + costbtw;
document.getElementById('totalofferte').innerHTML = totalofferte;
}
}
}
}
</script>
Edit:
Forgot my JQuery
$(".add-tablerow").click(function(){
$( ".table-body" ).append("<tr class='table-row'><td><input type='text' class='form-control' placeholder='Tijd'></td><td><input type='text' class='form-control' placeholder='Omschrijving'></td><td><input type='text' class='form-control' placeholder='Kosten'></td><td>€ 0,00</td><td>21%</td></tr>");
});
Using addNewRow method you can achieve the behaviour you are expecting
function addNewRow(){
var presentRows = $("#table-diensten > tbody > tr");
var newRowId = presentRows.length + 1;
$("#table-diensten").append(
'<tr id="' + newRowId + '">' +
'<td><input class="form-control" type="number" name="time_' + newRowId + '" id="time_' + newRowId + '"/></td>' +
'<td><input class="form-control" type="number" name="service_' + newRowId + '" id="service_' + newRowId + '"/></td>' +
'<td><input class="form-control" type="number" name="amount' + newRowId + '" id="amount' + newRowId + '"/></td>' +
'<td></td>' +
'<td></td>' +
'</tr>'
);
}
function totalofferte() {
var cost = document.getElementById('cost').value;
var time = document.getElementById('time').value;
if (cost > 0 && time > 0) {
var total = cost * time;
if (total > 0) {
document.getElementById('total').innerHTML = total;
var subtotal = total;
if (subtotal > 0) {
document.getElementById('subtotal').innerHTML = subtotal;
var costbtw = subtotal / 100 * 21;
document.getElementById('costbtw').innerHTML = costbtw;
var totalofferte = subtotal + costbtw;
document.getElementById('totalofferte').innerHTML = totalofferte;
}
}
}
}
.navigation {
width: 300px;
}
.mainmenu, .submenu {
list-style: none;
padding: 0;
margin: 0;
}
.mainmenu a {
display: block;
background-color: #CCC;
text-decoration: none;
padding: 10px;
color: #000;
}
.mainmenu li:hover a,
.mainmenu li.active a {
background-color: #C5C5C5;
}
.mainmenu li.active .submenu {
display: block;
max-height: 200px;
}
.submenu a {
background-color: #999;
}
.submenu a:hover {
background-color: #666;
}
.submenu {
overflow: hidden;
max-height: 0;
-webkit-transition: all 0.5s ease-out;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table-responsive table" id="table-diensten">
<thead>
<tr>
<th>Time</th>
<th>Service</th>
<th>amount</th>
<th>total</th>
<th>BTW</th>
</tr>
</thead>
<tbody class="table-body">
<tr class="table-row">
<td><input type="text" class="form-control" placeholder="time (in hours)" id="time" onchange="totalofferte()"></td>
<td><input type="text" class="form-control" placeholder="service"></td>
<td><input type="text" class="form-control" placeholder="Cost (per hour)" id="cost" onchange="totalofferte()"></td>
<td>€ <span id="total">0,00</span></td>
<td>21%</td>
</tr>
</tbody>
<tfoot>
<tr>
<td> </td>
<td> </td>
<td><strong>Subtotaal</strong></td>
<td>€ <span id="subtotal">0,00</span></td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td>21% BTW</td>
<td>€ <span id="costbtw">0,00</span></td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td class="table-total"><span class="total">Totaal</span></td>
<td class="table-total"><span class="total">€ <span id="totalofferte">0,00</span></span></td>
<td> </td>
</tr>
</tfoot>
</table>
add new service
its very simple. Frist create your element example:
var input = $("<input/>").attr({
name: 'EmailSend',
type: 'text',
value: true,
class: "YOURClass"
id: "YouRid"
});
Than append your crated input to your wish element. example: $( ".table-body" ).append(input)
Adding items in DOM through Javascript
In order to add new Items in your table with Native Javascript you will have to use one of the following
Element.insertAdjacentHTML()
Element.innerHTML
Node.appendChild()
If you want to use jQuery instead then you can try
.append()
.html()
Add custom attributes to DOM items
If you want to add a new attribute on a DOM element , you can do it with Native Javascript using the
element.setAttribute(name, value);
or with jQuery
.attr();
Loop through items
Now in order to "process" those new values each time , you need to iterate through all your inputs and carry your calculations. Iteration can be done in Native Javascript through the use of
Element.getElementsByTagName() If all inputs should be processed in your Table.
Document.getElementsByClassName() If you assign a specific class on each of your inputs and only those will be processed.
or if you want to use jQuery you could go on with
jQuery.each()

Categories

Resources