Is there anyway to show always rows modified in a FooTable - javascript

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;
}

Related

Setting color of specific row in table if the value inside is >1000

So like in the title i want to click the button set row to green if value inside is higher than 1000 i think i figured out the part with setting color im not sure about the button part here is
the specific part of code also the jsfiddle
$('.netto').filter(function makeGreen () {
return parseInt($.trim($(this).text()), 10) > 1000
}).closest('td').css('background-color', '#24AD36');
$(function() {
var vat = [{
display: "ZW",
value: "0",
},
{
display: "NP",
value: "0",
},
{
display: "0%",
value: "0",
},
{
display: "3%",
value: "3",
},
{
display: "8%",
value: "8",
},
{
display: "23%",
value: "23",
},
];
var options = ['<option value="">Wybierz VAT</option>'];
for (var i = 0; i < vat.length; i++) {
options.push('<option value="');
options.push(vat[i].value);
options.push('">');
options.push(vat[i].display);
options.push("</option>");
}
$(".obliczvat")
.html(options.join(""))
.change(function() {
var val = $(this).val();
if (val == 0) {
var ilosc = parseInt($(this).closest("td").prev().text(), 10);
var brutto = parseInt($(this).closest("td").next().text(), 10);
var ob = brutto * ilosc;
$(this).closest("td").next().next().text(ob);
}
if (val == 3) {
var ilosc = parseInt($(this).closest("td").prev().text(), 10);
var brutto = parseInt($(this).closest("td").next().text(), 10);
var ob = (brutto * ilosc) - brutto * ilosc * 0.03;
$(this).closest("td").next().next().text(ob);
}
if (val == 8) {
var ilosc = parseInt($(this).closest("td").prev().text(), 10);
var brutto = parseInt($(this).closest("td").next().text(), 10);
var ob = (brutto * ilosc) - brutto * ilosc * 0.08;
$(this).closest("td").next().next().text(ob);
}
if (val == 23) {
var ilosc = parseInt($(this).closest("td").prev().text(), 10);
var brutto = parseInt($(this).closest("td").next().text(), 10);
var ob = (brutto * ilosc) - brutto * ilosc * 0.23;
$(this).closest("td").next().next().text(ob);
}
});
$(function() {
$('.tabela tbody tr').each(function() {
var bruttoW = $('.bruttow', this).text();
var ilosc = parseInt($('.ilosc', this).text(), 10);
var brutto = parseInt($('.brutto', this).text(), 10);
var ob = (brutto * ilosc);
$('.bruttow', this).text(ob);
});
})
});
$('.netto').filter(function makeGreen() {
return parseInt($.trim($(this).text()), 10) > 1000
}).closest('td').css('background-color', '#24AD36');
body {
background: #34568B;
padding: 20px;
font-family: Helvetica;
}
#banner-message {
background: #fff;
border-radius: 4px;
padding: 20px;
font-size: 25px;
text-align: center;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}
#banner-message.alt {
background: #0084ff;
color: #fff;
margin-top: 40px;
width: 200px;
}
#banner-message.alt button {
background: #fff;
color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="tabela">
<tr>
<th>Lp.</th>
<th>Opis</th>
<th>Ilość</th>
<th>VAT</th>
<th>Kwota Brutto</th>
<th>Wartość Netto</th>
<th>Wartość Brutto</th>
</tr>
<tr>
<td>1</td>
<td>Palety</td>
<td class="ilosc">2</td>
<td>
<form name="Vat">
<select class="obliczvat"></select>
</form>
</td>
<td class="brutto">2000zł</td>
<td class="netto"></td>
<td class="bruttow"></td>
</tr>
<tr>
<td>2</td>
<td>Modernizjacja sprzętu komputerowego</td>
<td class="ilosc">8</td>
<td>
<form name="Vat">
<select class="obliczvat"></select>
</form>
</td>
<td class="brutto">120zł</td>
<td class="netto"></td>
<td class="bruttow"></td>
</tr>
<tr>
<td>3</td>
<td>modernizacja biura</td>
<td class="ilosc">4</td>
<td>
<form name="Vat">
<select class="obliczvat"></select>
</form>
</td>
<td class="brutto">5007zł</td>
<td class="netto"></td>
<td class="bruttow"></td>
</tr>
<tr>
<td>4</td>
<td>Paliwo</td>
<td class="ilosc">7</td>
<td>
<form name="Vat">
<select class="obliczvat"></select>
</form>
</td>
<td class="brutto">359zł</td>
<td class="netto"></td>
<td class="bruttow"></td>
</tr>
<tr>
<td>5</td>
<td>Zakup nowego Samochódu do floty</td>
<td class="ilosc">1</td>
<td>
<form name="Vat">
<select class="obliczvat"></select>
</form>
</td>
<td class="brutto">23755zł</td>
<td class="netto"></td>
<td class="bruttow"></td>
</tr>
</table>
<button type="button" name="green" onclick="makeGreen()">button</button>
https://jsfiddle.net/ramfwt31/
You basically had it, but the inline onclick was throwing it off so I added a jquery click and an id for your button so the function is called when the button is clicked
$(function() {
var vat = [{
display: "ZW",
value: "0",
},
{
display: "NP",
value: "0",
},
{
display: "0%",
value: "0",
},
{
display: "3%",
value: "3",
},
{
display: "8%",
value: "8",
},
{
display: "23%",
value: "23",
},
];
var options = ['<option value="">Wybierz VAT</option>'];
for (var i = 0; i < vat.length; i++) {
options.push('<option value="');
options.push(vat[i].value);
options.push('">');
options.push(vat[i].display);
options.push("</option>");
}
$(".obliczvat")
.html(options.join(""))
.change(function() {
var val = $(this).val();
if (val == 0) {
var ilosc = parseInt($(this).closest("td").prev().text(), 10);
var brutto = parseInt($(this).closest("td").next().text(), 10);
var ob = brutto * ilosc;
$(this).closest("td").next().next().text(ob);
}
if (val == 3) {
var ilosc = parseInt($(this).closest("td").prev().text(), 10);
var brutto = parseInt($(this).closest("td").next().text(), 10);
var ob = (brutto * ilosc) - brutto * ilosc * 0.03;
$(this).closest("td").next().next().text(ob);
}
if (val == 8) {
var ilosc = parseInt($(this).closest("td").prev().text(), 10);
var brutto = parseInt($(this).closest("td").next().text(), 10);
var ob = (brutto * ilosc) - brutto * ilosc * 0.08;
$(this).closest("td").next().next().text(ob);
}
if (val == 23) {
var ilosc = parseInt($(this).closest("td").prev().text(), 10);
var brutto = parseInt($(this).closest("td").next().text(), 10);
var ob = (brutto * ilosc) - brutto * ilosc * 0.23;
$(this).closest("td").next().next().text(ob);
}
});
$(function() {
$('.tabela tbody tr').each(function() {
var bruttoW = $('.bruttow', this).text();
var ilosc = parseInt($('.ilosc', this).text(), 10);
var brutto = parseInt($('.brutto', this).text(), 10);
var ob = (brutto * ilosc);
$('.bruttow', this).text(ob);
});
})
});
$('#green').on('click', function(event) {
$('.netto').filter(function makeGreen() {
return parseInt($.trim($(this).text()), 10) > 1000;
}).closest('td').css('background-color', '#24AD36');
});
body {
background: #34568B;
padding: 20px;
font-family: Helvetica;
}
#banner-message {
background: #fff;
border-radius: 4px;
padding: 20px;
font-size: 25px;
text-align: center;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}
#banner-message.alt {
background: #0084ff;
color: #fff;
margin-top: 40px;
width: 200px;
}
#banner-message.alt button {
background: #fff;
color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="tabela">
<tr>
<th>Lp.</th>
<th>Opis</th>
<th>Ilość</th>
<th>VAT</th>
<th>Kwota Brutto</th>
<th>Wartość Netto</th>
<th>Wartość Brutto</th>
</tr>
<tr>
<td>1</td>
<td>Palety</td>
<td class="ilosc">2</td>
<td>
<form name="Vat">
<select class="obliczvat"></select>
</form>
</td>
<td class="brutto">2000zł</td>
<td class="netto"></td>
<td class="bruttow"></td>
</tr>
<tr>
<td>2</td>
<td>Modernizjacja sprzętu komputerowego</td>
<td class="ilosc">8</td>
<td>
<form name="Vat">
<select class="obliczvat"></select>
</form>
</td>
<td class="brutto">120zł</td>
<td class="netto"></td>
<td class="bruttow"></td>
</tr>
<tr>
<td>3</td>
<td>modernizacja biura</td>
<td class="ilosc">4</td>
<td>
<form name="Vat">
<select class="obliczvat"></select>
</form>
</td>
<td class="brutto">5007zł</td>
<td class="netto"></td>
<td class="bruttow"></td>
</tr>
<tr>
<td>4</td>
<td>Paliwo</td>
<td class="ilosc">7</td>
<td>
<form name="Vat">
<select class="obliczvat"></select>
</form>
</td>
<td class="brutto">359zł</td>
<td class="netto"></td>
<td class="bruttow"></td>
</tr>
<tr>
<td>5</td>
<td>Zakup nowego Samochódu do floty</td>
<td class="ilosc">1</td>
<td>
<form name="Vat">
<select class="obliczvat"></select>
</form>
</td>
<td class="brutto">23755zł</td>
<td class="netto"></td>
<td class="bruttow"></td>
</tr>
</table>
<button type="button" id="green" name="green">button</button>

How to fix duplicate entries in number field in javascript

I have nine number fields to calculate. I need to check for duplicate entries in these 9 number fields and if found duplicate values, change the background color of the screen to 'red'. I'm not able to find solution for the mentioned.
I have created a table with 9 nine number fields to input the numbers and calculate the sum.
I searched for code to check for duplicate values in number fields, but found code to check for duplicate values in text fields.
<html>
<head>
<script>
function Sum() {
alert("hi");
var num1 = Number(document.getElementById("qty1").value);
var num2 = Number(document.getElementById("qty2").value);
var num3 = Number(document.getElementById("qty3").value);
var num4 = Number(document.getElementById("qty4").value);
var num5 = Number(document.getElementById("qty5").value);
var num6 = Number(document.getElementById("qty6").value);
var num7 = Number(document.getElementById("qty7").value);
var num8 = Number(document.getElementById("qty8").value);
var num9 = Number(document.getElementById("qty9").value);
var sum=num1+num2+num3+num4+num5+num6+num7+num8+num9
document.getElementById("answer").value = sum;
}
</script>
<style>
table>tbody>tr:nth-child(odd){
background-color: blue;
}
table>tbody>tr:nth-child(even){
background-color: green;
}
table>tbody>tr:nth-child(odd)>td:nth-child(odd){
background-color: green;
}
table>tbody>tr:nth-child(odd)>td:nth-child(even){
background-color: blue;
}
table>tbody>tr:nth-child(even)>td:nth-child(odd){
background-color: blue;
}
table>tbody>tr:nth-child(even)>td:nth-child(even){
background-color: green;
}
#sumtable th, #sumtable td{
padding:5px;
}
</style>
</head>
<title>Sum Box</title>
<body>
<table align="center" id="sumtable">
<tbody>
<tr>
<td>
<input type="number" placeholder="input1" value="input1"id="qty1"></td>
<td>
<input type="number" placeholder="input2" value="input2" id="qty2"></td>
<td>
<input type="number"placeholder="input3"value="input3"id="qty3"></td>
</tr>
<tr>
<td><input type="number" placeholder="input4" value="input4" id="qty4" ></td>
<td><input type="number" placeholder="input5" value="input5" id="qty5" ></td>
<td><input type="number" placeholder="input6" value="input6" id="qty6" ></td>
</tr>
<tr>
<td><input type="number" placeholder="input7" value="input7" id="qty7" ></td>
<td><input type="number" placeholder="input8" value="input8" id="qty8" ></td>
<td><input type="number" placeholder="input9" value="input9" id="qty9" ></td>
</tr>
</tbody>
</table>
<!-- Sum : <input type="text" name="total" id="total"/>
Sum-->
<div align="center">
<input type="button" onclick="Sum()" name="Sum" value="Sum" id="sum">
<input id="answer">
</div>
</body>
</html>
The above code generates 9 input number fields in table format to enter numbers and calculate the sum
Add your numbers to an array and loop through. One possible example, see https://codepen.io/anon/pen/yZaBrb:
var a = new Array(1,2,3,4,5,6,7,9,2,4);
var duplicate = false;
for (i=0;i<a.length;i++){
duplicate = false;
for(j=0;j<a.length;j++){
if(i != j && a[i]==a[j])
duplicate = true;
}
if(duplicate)
document.write('<span style="background-color:red;">')
document.write(a[i]);
if(duplicate)
document.write('</span>')
}
Create two events blur & keyup. On blur get the value from the input and push it in an array, on keyup check if the array contains the same value. If the value is present in the array then add a class to the target element or remove it
function Sum() {
alert("hi");
var num1 = Number(document.getElementById("qty1").value);
var num2 = Number(document.getElementById("qty2").value);
var num3 = Number(document.getElementById("qty3").value);
var num4 = Number(document.getElementById("qty4").value);
var num5 = Number(document.getElementById("qty5").value);
var num6 = Number(document.getElementById("qty6").value);
var num7 = Number(document.getElementById("qty7").value);
var num8 = Number(document.getElementById("qty8").value);
var num9 = Number(document.getElementById("qty9").value);
var sum = num1 + num2 + num3 + num4 + num5 + num6 + num7 + num8 + num9
document.getElementById("answer").value = sum;
}
let sumArray = []
document.querySelectorAll('input[type="number"]').forEach((item) => {
item.addEventListener('blur', (e) => {
sumArray.push(e.target.value)
})
item.addEventListener('keyup', (e) => {
if (sumArray.indexOf(e.target.value) !== -1) {
e.target.parentNode.classList.add('error')
} else if (e.target.parentNode.classList.contains('error')) {
e.target.parentNode.classList.remove('error')
}
})
})
table>tbody>tr:nth-child(odd) {
background-color: blue;
}
table>tbody>tr:nth-child(even) {
background-color: green;
}
table>tbody>tr:nth-child(odd)>td:nth-child(odd) {
background-color: green;
}
table>tbody>tr:nth-child(odd)>td:nth-child(even) {
background-color: blue;
}
table>tbody>tr:nth-child(even)>td:nth-child(odd) {
background-color: blue;
}
table>tbody>tr:nth-child(even)>td:nth-child(even) {
background-color: green;
}
#sumtable th,
#sumtable td {
padding: 5px;
}
.error {
border: 2px solid red;
}
<title>Sum Box</title>
<body>
<table align="center" id="sumtable">
<tbody>
<tr>
<td>
<input type="number" placeholder="input1" value="input1" id="qty1"></td>
<td>
<input type="number" placeholder="input2" value="input2" id="qty2"></td>
<td>
<input type="number" placeholder="input3" value="input3" id="qty3"></td>
</tr>
<tr>
<td><input type="number" placeholder="input4" value="input4" id="qty4"></td>
<td><input type="number" placeholder="input5" value="input5" id="qty5"></td>
<td><input type="number" placeholder="input6" value="input6" id="qty6"></td>
</tr>
<tr>
<td><input type="number" placeholder="input7" value="input7" id="qty7"></td>
<td><input type="number" placeholder="input8" value="input8" id="qty8"></td>
<td><input type="number" placeholder="input9" value="input9" id="qty9"></td>
</tr>
</tbody>
</table>
<!-- Sum : <input type="text" name="total" id="total"/>
Sum-->
<div align="center">
<input type="button" onclick="Sum()" name="Sum" value="Sum" id="sum">
<input id="answer">
</div>
its pretty simple just put same class in input field and loop through it like
In Html ,
<td>
<input type="number" class="checkSame" placeholder="input1" value="input1"id="qty1"></td>
<td>
<input type="number" class="checkSame" placeholder="input2" value="input2" id="qty2"></td>
<td>
<input type="number" class="checkSame" placeholder="input3"value="input3"id="qty3"></td>
then in javascript ,
var inputs = document.getElementsByClassName("checkSame");
var temp;
var count = 1;
for(var i = 0; i < inputs .length; i++)
{
temp = document.getElementsByClassName("checkSame")[i].value;
if(temp == document.getElementsByClassName("checkSame")[count++].value)
{
//change your background color here
break;
}
}
i think it works.
I hope this will help you to find duplicate fields
function Sum() {
alert("hi");
let arr = [];
let sum;
let duplicate = false;
for (let i = 1; i <= 9; i++) {
let num = Number(document.getElementById(`qty${i}`).value);
let indexOfDuplicateNum = arr.indexOf(num);
if (indexOfDuplicateNum > -1){
duplicate = true;
alert('Duplicate value found!');
document.getElementsByTagName('body')[0].style.background = 'red';
document.getElementById(`qty${i}`).classList.add('duplicate-error');
document.getElementById(`qty${indexOfDuplicateNum+1}`).classList.add('duplicate-error');
break;
} else{
//remove error class if value is not duplicate
document.getElementById(`qty${i}`).classList.remove('duplicate-error');
arr.push(num);
sum = arr.reduce((a, b) => a+b, 0);
}
}
if (!duplicate) {
document.getElementById('answer').value = sum;
document.getElementsByTagName('body')[0].style.background = 'white';
}
}
.duplicate-error {
border: 2px solid red;
}
table>tbody>tr:nth-child(odd){
background-color: blue;
}
table>tbody>tr:nth-child(even){
background-color: green;
}
table>tbody>tr:nth-child(odd)>td:nth-child(odd){
background-color: green;
}
table>tbody>tr:nth-child(odd)>td:nth-child(even){
background-color: blue;
}
table>tbody>tr:nth-child(even)>td:nth-child(odd){
background-color: blue;
}
table>tbody>tr:nth-child(even)>td:nth-child(even){
background-color: green;
}
#sumtable th, #sumtable td{
padding:5px;
}
<html>
<head>
<title>Sum Calculator</title>
</head>
<title>Sum Box</title>
<body>
<table align="center" id="sumtable">
<tbody>
<tr>
<td>
<input type="number" placeholder="input1" value="input1"id="qty1"></td>
<td>
<input type="number" placeholder="input2" value="input2" id="qty2"></td>
<td>
<input type="number"placeholder="input3"value="input3"id="qty3"></td>
</tr>
<tr>
<td><input type="number" placeholder="input4" value="input4" id="qty4" ></td>
<td><input type="number" placeholder="input5" value="input5" id="qty5" ></td>
<td><input type="number" placeholder="input6" value="input6" id="qty6" ></td>
</tr>
<tr>
<td><input type="number" placeholder="input7" value="input7" id="qty7" ></td>
<td><input type="number" placeholder="input8" value="input8" id="qty8" ></td>
<td><input type="number" placeholder="input9" value="input9" id="qty9" ></td>
</tr>
</tbody>
</table>
<!-- Sum : <input type="text" name="total" id="total"/>
Sum-->
<div align="center">
<input type="button" onclick="Sum()" name="Sum" value="Sum" id="sum">
<input id="answer">
</div>
</body>
</html>

How jQuery invoices form and delete how buttons add

I am currently working on a dynamic invoice system for myself. But I can't make it work correctly.
I want to add a delete button to this form but I cannot do so.
I have an invoice table like this in HTML:
$('#addRow').click(function () {
addItem();
});
$('#items_table').on('keyup', '.update', function () {
var key = event.keyCode || event.charCode; // if the user hit del or backspace, dont do anything
if( key == 8 || key == 46 ) return false;
calculateTotals();
});
$('#taxPercentage').change(function () {
calculateTotals(); // user changed tax percentage, recalculate everything
});
function calculateTotals(){
// get all of the various input typs from the rows
// each will be any array of elements
var nameElements = $('.row-name');
var quantityElements = $('.row-quantity');
var taxElements = $('.row-tax');
var priceElements = $('.row-price');
var totalElements = $('.row-total');
// get the bottom table elements
var taxPercentageElement =$('#taxPercentage');
var subTotalElement =$('#subTotal');
var totalTaxElement =$('#totalTax');
var grandTotalElement =$('#grandTotal');
var subTotal=0;
var taxTotal=0;
var grandTotal=0;
$(quantityElements).each(function(i,e){
// get all the elements for the current row
var nameElement = $('.row-name:eq(' + i + ')');
var quantityElement = $('.row-quantity:eq(' + i + ')');
var taxElement = $('.row-tax:eq(' + i + ')');
var priceElement = $('.row-price:eq(' + i + ')');
var totalElement = $('.row-total:eq(' + i + ')');
// get the needed values from this row
var qty = quantityElement.val().trim().replace(/[^0-9$.,]/g, ''); // filter out non digits like letters
qty = qty == '' ? 0 : qty; // if blank default to 0
quantityElement.val(qty); // set the value back, in case we had to remove soemthing
var price = priceElement.val().trim().replace(/[^0-9$.,]/g, '');
price = price == '' ? 0 : price; // if blank default to 0
priceElement.val(price); // set the value back, in case we had to remove soemthing
// get/set row tax and total
// also add to our totals for later
var rowPrice = (price * 1000) * qty
subTotal = subTotal + rowPrice;
var tax = taxPercentageElement.val() * rowPrice;
taxElement.val((tax / 1000).toFixed(2));
taxTotal = taxTotal + tax;
var total = rowPrice + tax
totalElement.val((total / 1000).toFixed(2));
grandTotal = grandTotal + total;
});
// set the bottom table values
subTotalElement.val((subTotal / 1000).toFixed(2));
totalTaxElement.val((taxTotal / 1000).toFixed(2));
grandTotalElement.val((grandTotal / 1000).toFixed(2));
}
function addItem() {
var itemRow =
'<tr>' +
'<td><input type="text" class="form-control row-name" placeholder="Item name" /></td>' +
'<td><input type="text" class="form-control update row-quantity" placeholder="Quantity" /></td>' +
'<td><input type="text" class="form-control update row-tax" placeholder="Tax" /></td>' +
'<td><input type="text" class="form-control update row-price" placeholder="Price" /></td>' +
'<td><input type="text" class="form-control row-total" disabled placeholder="0,00" /></td>' +
'</tr>';
$("#items_table").append(itemRow);
}
addItem(); //call function on load to add the first item
button{
font-size:18px;
}
.myTable {
background-color:#ffaa56;
}
.myTable {
border-collapse: collapse;
border-spacing: 0;
width:100%;
height:100%;
margin:0px;
padding:0px;
}
.myTable tr:last-child td:last-child {
-moz-border-radius-bottomright:0px;
-webkit-border-bottom-right-radius:0px;
border-bottom-right-radius:0px;
}
.myTable tr:first-child td:first-child {
-moz-border-radius-topleft:0px;
-webkit-border-top-left-radius:0px;
border-top-left-radius:0px;
}
.myTable tr:first-child td:last-child {
-moz-border-radius-topright:0px;
-webkit-border-top-right-radius:0px;
border-top-right-radius:0px;
}
.myTable tr:last-child td:first-child {
-moz-border-radius-bottomleft:0px;
-webkit-border-bottom-left-radius:0px;
border-bottom-left-radius:0px;
}
.myTable tr:hover td {
}
#items_table tr:nth-child(odd) {
background-color:#ffffff;
}
#items_table tr:nth-child(even) {
background-color:#ffd0a3;
}
.myTable td {
vertical-align:middle;
border:1px solid #000000;
border-width:0px 1px 1px 0px;
text-align:left;
padding:7px;
font-size:10px;
font-family:Arial;
font-weight:normal;
color:#000000;
}
.myTable tr:last-child td {
border-width:0px 1px 0px 0px;
}
.myTable tr td:last-child {
border-width:0px 0px 1px 0px;
}
.myTable tr:last-child td:last-child {
border-width:0px 0px 0px 0px;
}
html page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button id="addRow">Add a row</button><br><br>
<table class="myTable">
<thead>
<tr>
<th>Item Name</th>
<th>Quantity</th>
<th>Tax</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<tbody id="items_table"></tbody>
<tfoot>
<tr>
<th>Item Name</th>
<th>Quantity</th>
<th>Tax</th>
<th>Price</th>
<th>Total</th>
</tr>
</tfoot>
</table>
<br>
<br>
<table class="myTable" style="width:70%">
<thead>
<tr>
<th>Tax Percentage</th>
<th>Sub Total</th>
<th>Total Tax</th>
<th>Grand Total</th>
</tr>
</thead>
<tbody id="items_table">
<tr>
<td>
<select name="" id="taxPercentage" class="form-control">
<option value=".10">10%</option>
<option value=".15">15%</option>
</select>
<td><input type="text" class="form-control" id="subTotal" disabled placeholder="0,00" /></td>
<td><input type="text" class="form-control" id="totalTax" disabled placeholder="0,00" /></td>
<td><input type="text" class="form-control" id="grandTotal" disabled placeholder="0,00" /></td>
</tr>
</tbody>
<tfoot>
</tfoot>
</table>
I am currently out of ideas on how to do this correctly. So, all I need is once I filled 1 item row, the tax gets in the total table added, and once I change that tax in that row, it changes below as well, and the price has to be changed as well.
Can someone set me on the right track?
I want to add delete button to this form but I can not do it
The key here is to understand that event handlers usually can be set only on the elements that are present on the page at the moment of setting. Your code failed because you add rows dynamically - they didn't exist when you tried to assign an event handler. However, jQuery provides us with the special form of on() function that covers what we need in this case:
$('already present parent element selector').on("click", "existing/added later element selector", function () {
//code
});
So, in order to sort out your problem your code should look like this:
$('body').on("click", "#delRow", function () {
delItem($(this));
});
function delItem(elem) {
elem.parents("tr").remove();
calculateTotals();
}
Note that you have to add #delRow button to your template in addItem() function and corresponding <th> cells in the markup.
Regarding the whole thing, I would also make the tax cell disabled because it wouldn't make sense if users could edit it since the tax sum is defined by percent value below (either 10% or 15%). And the taxes are usually imposed by the govs. and known in advance. I mean you cannot just pay 5.745632% instead of 15% defined by a law.
Also I spotted one minor issue: when I remove symbols in the price cell the update doesn't get executed and the related cells' values don't change accordingly. You might want to read about input event on MDN.
In general it works fine if I understood your ideas correctly:
$('#addRow').on("click", function () {
addItem();
});
$('body').on("click", "#delRow", function () {
delItem($(this));
});
$('#items_table').on('input', '.update', function () {
var key = event.keyCode || event.charCode; // if the user hit del or backspace, dont do anything
if( key == 8 || key == 46 ) return false;
calculateTotals();
});
$('#taxPercentage').change(function () {
calculateTotals(); // user changed tax percentage, recalculate everything
});
function calculateTotals(){
// get all of the various input typs from the rows
// each will be any array of elements
var nameElements = $('.row-name');
var quantityElements = $('.row-quantity');
var taxElements = $('.row-tax');
var priceElements = $('.row-price');
var totalElements = $('.row-total');
// get the bottom table elements
var taxPercentageElement =$('#taxPercentage');
var subTotalElement =$('#subTotal');
var totalTaxElement =$('#totalTax');
var grandTotalElement =$('#grandTotal');
var subTotal=0;
var taxTotal=0;
var grandTotal=0;
$(quantityElements).each(function(i,e){
// get all the elements for the current row
var nameElement = $('.row-name:eq(' + i + ')');
var quantityElement = $('.row-quantity:eq(' + i + ')');
var taxElement = $('.row-tax:eq(' + i + ')');
var priceElement = $('.row-price:eq(' + i + ')');
var totalElement = $('.row-total:eq(' + i + ')');
// get the needed values from this row
var qty = quantityElement.val().trim().replace(/[^0-9$.,]/g, ''); // filter out non digits like letters
qty = qty == '' ? 0 : qty; // if blank default to 0
quantityElement.val(qty); // set the value back, in case we had to remove soemthing
var price = priceElement.val().trim().replace(/[^0-9$.,]/g, '');
price = price == '' ? 0 : price; // if blank default to 0
priceElement.val(price); // set the value back, in case we had to remove soemthing
// get/set row tax and total
// also add to our totals for later
var rowPrice = (price * 1000) * qty
subTotal = subTotal + rowPrice;
var tax = taxPercentageElement.val() * rowPrice;
taxElement.val((tax / 1000).toFixed(2));
taxTotal = taxTotal + tax;
var total = rowPrice + tax
totalElement.val((total / 1000).toFixed(2));
grandTotal = grandTotal + total;
});
// set the bottom table values
subTotalElement.val((subTotal / 1000).toFixed(2));
totalTaxElement.val((taxTotal / 1000).toFixed(2));
grandTotalElement.val((grandTotal / 1000).toFixed(2));
}
function delItem(elem) {
elem.parents("tr").remove();
calculateTotals();
}
function addItem() {
var itemRow =
'<tr>' +
'<td><button id="delRow">Delete</button></td><td><input type="text" class="form-control row-name" placeholder="Item name" /></td>' +
'<td><input type="text" class="form-control update row-quantity" placeholder="Quantity" /></td>' +
'<td><input type="text" disabled class="form-control update row-tax" placeholder="Tax" /></td>' +
'<td><input type="text" class="form-control update row-price" placeholder="Price" /></td>' +
'<td><input type="text" class="form-control row-total" disabled placeholder="0,00" /></td>' +
'</tr>';
$("#items_table").append(itemRow);
}
addItem(); //call function on load to add the first item
button{
font-size:18px;
}
.myTable {
background-color:#ffaa56;
}
.myTable {
border-collapse: collapse;
border-spacing: 0;
width:100%;
height:100%;
margin:0px;
padding:0px;
}
.myTable tr:last-child td:last-child {
-moz-border-radius-bottomright:0px;
-webkit-border-bottom-right-radius:0px;
border-bottom-right-radius:0px;
}
.myTable tr:first-child td:first-child {
-moz-border-radius-topleft:0px;
-webkit-border-top-left-radius:0px;
border-top-left-radius:0px;
}
.myTable tr:first-child td:last-child {
-moz-border-radius-topright:0px;
-webkit-border-top-right-radius:0px;
border-top-right-radius:0px;
}
.myTable tr:last-child td:first-child {
-moz-border-radius-bottomleft:0px;
-webkit-border-bottom-left-radius:0px;
border-bottom-left-radius:0px;
}
.myTable tr:hover td {
}
#items_table tr:nth-child(odd) {
background-color:#ffffff;
}
#items_table tr:nth-child(even) {
background-color:#ffd0a3;
}
.myTable td {
vertical-align:middle;
border:1px solid #000000;
border-width:0px 1px 1px 0px;
text-align:left;
padding:7px;
font-size:10px;
font-family:Arial;
font-weight:normal;
color:#000000;
}
.myTable tr:last-child td {
border-width:0px 1px 0px 0px;
}
.myTable tr td:last-child {
border-width:0px 0px 1px 0px;
}
.myTable tr:last-child td:last-child {
border-width:0px 0px 0px 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="addRow">Add a row</button><br><br>
<table class="myTable">
<thead>
<tr><th>Delete</th>
<th>Item Name</th>
<th>Quantity</th>
<th>Tax</th>
<th>Price per unit</th>
<th>Total</th>
</tr>
</thead>
<tbody id="items_table"></tbody>
<tfoot>
<tr><th>Delete</th>
<th>Item Name</th>
<th>Quantity</th>
<th>Tax</th>
<th>Price per unit</th>
<th>Total</th>
</tr>
</tfoot>
</table>
<br>
<br>
<table class="myTable" style="width:70%">
<thead>
<tr>
<th>Tax Percentage</th>
<th>Sub Total</th>
<th>Total Tax</th>
<th>Grand Total</th>
</tr>
</thead>
<tbody id="items_table">
<tr>
<td>
<select name="" id="taxPercentage" class="form-control">
<option value=".10">10%</option>
<option value=".15">15%</option>
</select>
<td><input type="text" class="form-control" id="subTotal" disabled placeholder="0,00" /></td>
<td><input type="text" class="form-control" id="totalTax" disabled placeholder="0,00" /></td>
<td><input type="text" class="form-control" id="grandTotal" disabled placeholder="0,00" /></td>
</tr>
</tbody>
<tfoot>
</tfoot>
</table>
As for your additional question - you can choose a locale to treat numbers as money in your country's format. It can be done by toLocaleString():
var num1 = 145636,
num2 = 145636;
console.log(num1.toLocaleString('en-US', {style: 'currency', currency: 'USD'})); // US format - 145,636
console.log(num2.toLocaleString('en-IN', {style: 'currency', currency: 'INR'})); // Indian format - 1,45,636
How can I separate the numbers that I write to price into a comma?
sample:
1,500
1,456,36

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()

Javascript Functions for Form are not Displaying with textContent

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>

Categories

Resources