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()
Related
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;
}
I have tried to put a horizontal line on top of a clone table without adding any new html tag such as <p>, <div> or any similar. I have no clue to make it happening.
I've also tried by adding a style.border when a click event is detected, but it seen like only can get the id after the html page was loaded. Probably I'm doing something wrong here.
This is my code:
function newtable(id) {
var table = document.getElementById(id).lastChild;
var tr = table.lastChild;
var lastId = Number(tr.getAttribute('id').split('_')[1]);
var trClone = tr.cloneNode(true);
trClone.setAttribute('id', id + '_' + (lastId + 1));
trClone.lastChild.childNodes[0].setAttribute('onclick', 'remove(' + id + ',' + (lastId + 1) + ')');
table.appendChild(trClone);
var b = document.getElementById(id).style.borderBottomColor = "red"; //i try to add horizontal line here every time this function is trigger.
}
<table>
<tbody>
<tr>
<td>
<table id="1">
<tr>
<td>
<span>Name</span> <input type="text" value="Peterson" />
</td>
<td>
<span>Country</span><input type="text" value="England" />
</td>
<td>
<span>Email</span><input type="text" value="Peterson#gmail.com" />
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<input type="button" value="Add" onclick="newtable(10)" />
</td>
</tr>
</tbody>
</table>
Expected result every time click on add button will clone table and draw horizontal line on top of new clone table.
I tried to fix some minor errors:
I replaced the lastChild() with table.rows[lastRowIndex] to get the last element of a table.
Added a new newId to update the ids.
I'm using mainTable.insertRow(mainTable.rows.length); to add a row in the <tbody> of the main-tbl.
Added a .adder class to the <tr> element that contains the button.
I filter the first and last children also the .adder class using this query: tr:not(.adder):not(:first-child):not(:last-child)
Here is a working example:
let mainTable = document.getElementById('main-tbl');
function addNewRow(id) {
let table = document.getElementById('inner-tbl');
let lastRowIndex = table.rows.length - 1;
let trOrigin = table.rows[lastRowIndex];
let lastId = Number(trOrigin.getAttribute('id').split('_')[1]);
let newId = 'item_' + (lastId + 1);
trOrigin.setAttribute('id', newId);
let trClone = trOrigin.cloneNode(true);
let lastCellIndex = trClone.cells.length - 1;
// Insert a row in the table at the last row
let newRow = mainTable.insertRow(mainTable.rows.length);
newRow.setAttribute('id', newId);
newRow.innerHTML = trClone.innerHTML;
newRow.cells[lastCellIndex].setAttribute('onclick', 'remove(' + id + ',' + (lastId + 1) + ')');
}
body {
overflow-y: scroll;
}
#main-tbl>tbody>tr:not(.adder):not(:first-child):not(:last-child)>td {
// border-top: 1px solid #000;
background-color: red;
}
#main-tbl {
width: 100%;
table-layout: fixed;
overflow-wrap: break-word;
}
<table id="main-tbl">
<tbody>
<tr>
<td>
<table id="inner-tbl">
<tr id="item_0">
<td>
<span>Name</span> <input type="text" value="Peterson" />
</td>
<td>
<span>Country</span><input type="text" value="England" />
</td>
<td>
<span>Email</span><input type="text" value="Peterson#gmail.com" />
</td>
</tr>
</table>
</td>
</tr>
<tr class="adder">
<td>
<input type="button" value="Add" onclick="addNewRow()" />
</td>
</tr>
</tbody>
</table>
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)
);
My Requirment:
I have table with quantity cell as editable when change quantity it need to multiply with other parent td value.and sum the column values .
(i.e) if i change quantity to 2 then the parent rows need multiply by 2 & columns get value get added
I done all the calculation part the only thing when i delete or change the quantity the calculated value remain same how to revert back to old values
Here is my fiddle
Fiddle link
$(document).ready(function(){
$('.quantity').on('change, keyup',function(){
var val=$(this).text();
// To avoid auto inc while pressing arrow keys
var preVal =$(this).data('prevval');
<!-- console.log(preVal); -->
if(preVal && preVal == val){
return;
}
$(this).data('prevval',val);
//To avoid auto inc while pressing arrow keys //
if(val =='' || isNaN(val) || val < 1){
return;
}
$(this).siblings().each(function(){
var tbvalue=$(this).text();
var result= parseInt(tbvalue)*parseInt(val);
$(this).text(result);
})
autoSum();
});
autoSum();
});
function autoSum(){
for (var i = 1; i < 8; i++) {
var sum = 0;
$('.auto_sum>tbody>tr>td:nth-child(' + i + ')').each(function() {
sum += parseInt($(this).text()) || 0;
});
// set total in last cell of the column
$('.auto_sum>tbody>tr>td:nth-child(' + i + ')').last().html(sum);
// $('.auto_sum>tbody>tr>td:nth-child(' + i + ')').last().toggleClass('total');
}
}
.total {
background-color: #000;
color: #fff;
font-weight: bold;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
<h2>Table calculation</h2>
<p>Calculaton</p>
<table class="auto_sum table table-hover">
<thead>
<tr>
<th>value1</th>
<th>value2</th>
<th>value3</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td>10</td>
<td>5</td>
<td>4</td>
<td class="quantity" type="number" contenteditable>1</td>
</tr>
<tr>
<td>8</td>
<td type>2</td>
<td>3</td>
<td class="quantity" type="number" contenteditable>1</td>
</tr>
<tr>
<td>20</td>
<td>3</td>
<td>5</td>
<td class="quantity" type="number" contenteditable>1</td>
</tr>
<tr class="total">
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>
</div>
Inside every row, with the td that store the numbers to be multiplied, keep the original numbers in a data-val attribute in the td, and multiply your content editable value with that. Display the multiplied value as the td text. One change here is that, when you delete the value of contenteditable cell, it takes it as 1 for row calculation, but does not consider it for column multiplication.
HTML part
<div class="container">
<h2>Table calculation</h2>
<p>Calculaton</p>
<table class="auto_sum table table-hover">
<thead>
<tr>
<th>value1</th>
<th>value2</th>
<th>value3</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td data-val="10">10</td>
<td data-val="5">5</td>
<td data-val="4">4</td>
<td class="quantity" type="number" contenteditable>1</td>
</tr>
<tr>
<td data-val="8">8</td>
<td data-val="2">2</td>
<td data-val="3">3</td>
<td class="quantity" type="number" contenteditable>1</td>
</tr>
<tr>
<td data-val="20">20</td>
<td data-val="3">3</td>
<td data-val="5">5</td>
<td class="quantity" type="number" contenteditable>1</td>
</tr>
<tr class="total">
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>
</div>
JS Part
$(document).ready(function(){
$('.quantity').on('change, keyup',function(){
var val=$(this).text();
// To avoid auto inc while pressing arrow keys
var preVal =$(this).data('prevval');
$(this).data('prevval',val);
//To avoid auto inc while pressing arrow keys //
if(val =='' || isNaN(val) || val < 1 || val == undefined){
val = 1;
}
$(this).siblings().each(function(){
var tbvalue=$(this).data("val");
var result= parseInt(tbvalue)*parseInt(val);
$(this).text(result);
});
autoSum();
});
autoSum();
});
function autoSum(){
for (var i = 1; i <= 4; i++) {
var sum = 0;
var tdBoxes = $('.auto_sum>tbody>tr>td:nth-child(' + i + ')');
for(var j=0; j<tdBoxes.length-1;j++)
{
var value = $(tdBoxes[j]).text();
//alert(value);
sum += (value == undefined || value == "")? 0 : parseInt(value);
}
// set total in last cell of the column
$('.auto_sum>tbody>tr>td:nth-child(' + i + ')').last().html(sum);
// $('.auto_sum>tbody>tr>td:nth-child(' + i + ')').last().toggleClass('total');
}
}
All details are commented in working demo. I added <form>, <output>, <input type='number'> and <input type='hidden'>. Also I don't remember <td> having a type attribute or a value of number either.
With the combination of the right elements and attributes (and maybe even a little CSS), you don't have to write so much JS/jQ because there many aspects of form functions built within HTML.
Demo
// Reference the <form>
var main = document.forms.main;
// Reference of all of <input> and <output> of <form>
var field = main.elements;
/* Register the input event on the <form>
|| ANY input event triggered within <form> will...
*/
main.addEventListener('input', function(e) {
// Check to see which field is the user inputing into
if (e.target !== e.currentTarget) {
// Reference that field
var input = document.getElementById(e.target.id);
// console.log(input.value);
// Get the row of the field
var row = input.parentNode.parentNode;
// console.log(row);
/* Gather all hidden fields of that row into a NodeList
|| and convert that NodeList into an array.
*/
var rowArray = Array.from(row.querySelectorAll('[type=hidden]'));
// console.log(rowArray);
// On each hidden field, perform the following function...
rowArray.forEach(function(cel, idx) {
// Get the value of hidden field
const base = cel.value;
// Find the <output> that comes after the hidden field
var output = cel.nextElementSibling;
/* Calculate the product of the hidden field's value
|| and the input field's value
*/
var val = parseInt(base, 10) * parseInt(input.value, 10);
// Display the prouct in the <output>
output.value = val;
});
/* Because we registered the input event on the <form>,
|| we have many ways to manipulate the <form>'s fields.
|| In this demo we have been using:
|| HTMLFormElement and HTMLFormControlsCollection interfaces
|| https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement
|| http://www.dyn-web.com/tutorials/forms/references.php#dom0
*/
field.out1.value = Number(field.o1a.value) + Number(field.o1b.value) + Number(field.o1c.value);
field.out2.value = Number(field.o2a.value) + Number(field.o2b.value) + Number(field.o2c.value);
field.out3.value = Number(field.o3a.value) + Number(field.o3b.value) + Number(field.o3c.value);
field.out4.value = Number(field.out1.value) + Number(field.out2.value) + Number(field.out3.value);
}
});
.total {
background-color: #000;
color: #fff;
font-weight: bold;
}
input,
output {
display: inline-block;
font: inherit;
width: 6ch;
border: 0;
text-align: center;
}
.quantity input {
padding-top: .5em;
outline: 0;
}
-
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<style>
</style>
</head>
<body>
<div class="container">
<form id='main'>
<table class="auto_sum table table-hover">
<thead>
<caption>
<h2>Table Calculation</h2>
<h3>Quanities</h3>
</caption>
<tr>
<th>Value1</th>
<th>Value2</th>
<th>Value3</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr id='rowA'>
<td>
<!--[0][1]-->
<input id='v1a' type='hidden' value='10'>
<output id='o1a'>0</output>
</td>
<td>
<!--[2][3]-->
<input id='v2a' type='hidden' value='5'>
<output id='o2a'>0</output>
</td>
<td>
<!--[4][5]-->
<input id='v3a' type='hidden' value='4'>
<output id='o3a'>0</output>
</td>
<td class="quantity">
<!--[6]-->
<input id='qa' type='number' value='0' max='999' min='0'>
</td>
</tr>
<tr id='rowB'>
<td>
<!--[7][8]-->
<input id='v1b' type='hidden' value='8'>
<output id='o1b'>0</output>
</td>
<td>
<!--[9][10]-->
<input id='v2b' type='hidden' value='2'>
<output id='o2b'>0</output>
</td>
<td>
<!--[11][12]-->
<input id='v3b' type='hidden' value='3'>
<output id='o3b'>0</output>
</td>
<td class="quantity">
<!--[13]-->
<input id='qb' type='number' value='0' max='999' min='0'>
</td>
</tr>
<tr id='rowC'>
<td>
<!--[14][15]-->
<input id='v1c' type='hidden' value='20'>
<output id='o1c'>0</output>
</td>
<td>
<!--[16][17]-->
<input id='v2c' type='hidden' value='3'>
<output id='o2c'>0</output>
</td>
<td>
<!--[18][19]-->
<input id='v3c' type='hidden' value='5'>
<output id='o3c'>0</output>
</td>
<td class="quantity">
<!--[20]-->
<input id='qc' type='number' value='0' max='999' min='0'>
</td>
</tr>
<tr class="total">
<td>
<!--[21]-->
<output id='out1' for='o1a o1b o1c'>0</output>
</td>
<td>
<!--[22]-->
<output id='out2' for='o2a o2b o2c'>0</output>
</td>
<td>
<!--[23]-->
<output id='out3' for='o3a o3b o3c'>0</output>
</td>
<td>
<!--[24]-->
<output id='out4' for='out1 out2 out3'>0</output>
</td>
</tr>
</tbody>
</table>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
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>