I have this HTML Code from Invoice:-
<tr>
<td colspan="3" class="blank"></td>
<td colspan="2" class="total-line">Subtotal Rs.</td>
<td td class="total-value">
<textarea id="subtotal" name="i_subt" readonly="readonly"></textarea>
</td>
</tr>
<tr>
<td colspan="3" class="blank"></td>
<td colspan="2" class="total-line">CGST (2.5%) Rs.</td>
<td td class="total-value">
<textarea id="cgst" name="i_cgst">.00</textarea>
</td>
</tr>
<tr>
<td colspan="3" class="blank"></td>
<td colspan="2" class="total-line">SGST (2.5%) Rs.</td>
<td td class="total-value">
<textarea id="sgst" name="i_sgst">.00</textarea>
</td>
</tr>
<tr>
<td colspan="3" class="blank"></td>
<td colspan="2" class="total-line">Total Rs. </td>
<td class="total-value">
<textarea id="total" name="i_ttl" readonly="readonly"></textarea>
</td>
</tr>
i have this code, I want too add 2 taxes namely CGST (2.5%) & SGST (2.5%) in subtotal...
function update_total() {
var total = 0;
$('.price').each(function(i){
price = $(this).html().replace("$","");
if (!isNaN(price)) total += Number(price);
});
total = roundNumber(total,2);
$('#subtotal').html(total);
//NEED some Code here to add CGST & SGST to Total
$('#total').html(total);
update_balance();
}
My Code is adding "Qty * Unit Price = Item total" of each item in Subtotal Perfectly. I need some code to add CGST * SGST in Sub-Total to make Total.
Use the equation (total * 2.5)/100 to find GST # 2.5%.
See below code to find the GST of Subtotal and add it to total
function update_total() {
var total = 0;
var gst = 0;
$('.price').each(function(i){
price = $(this).html().replace("$","");
if (!isNaN(price)) total += Number(price);
});
total = roundNumber(total,2);
$('#subtotal').html(total);
//NEED some Code here to add CGST & SGST to Total
gst = roundNumber((total * 2.5)/100,2);
$('#cgst').html(gst);
$('#sgst').html(gst);
$('#total').html(total + gst);
update_balance();
}
Related
I am unsure of what I have done wrong in my simple sales tax calculator. When I press submit I want a dollar amount of the item cost plus sales tax to be shown but instead I see total tip $functionround(){[native code]}.
//calculation
var total = (itemCost * salesTax + itemCost);
total = Math.round
total = Math.round
In the line above you are assigning the value of the function Math.round to the variable total. Instead you probably want to assign the value returned by the function Math.round to your total variable like this:
total = Math.round(total)
You should consider those codes on the calculation. Here is a simple tax calculator and it works well:
function fmtPrice(value) {
result="$"+Math.floor(value)+".";
var cents=100*(value-Math.floor(value))+0.5;
result += Math.floor(cents/10);
result += Math.floor(cents%10);
return result;
}
function compute() {
var unformatted_tax = (document.forms[0].cost.value)*(document.forms[0].tax.value);
document.forms[0].unformatted_tax.value=unformatted_tax;
var formatted_tax = fmtPrice(unformatted_tax);
document.forms[0].formatted_tax.value=formatted_tax;
var cost3= eval( document.forms[0].cost.value );
cost3 += eval( (document.forms[0].cost.value)*(document.forms[0].tax.value) );
var total_cost = fmtPrice(cost3);
document.forms[0].total_cost.value=total_cost;
}
function resetIt() {
document.forms[0].cost.value="19.95"; // cost of product
document.forms[0].tax.value=".06"; // tax value
document.forms[0].unformatted_tax.value="";
document.forms[0].formatted_tax.value="";
document.forms[0].total_cost.value="";
}
<CENTER>
<FORM>
<TABLE BORDER=2 WIDTH=300 CELLPADDING=3>
<TR>
<TD align="center"><FONT SIZE=+1><STRONG>Cost</STRONG></FONT>
<TD align="center"><FONT SIZE=+1><STRONG>Tax</STRONG></FONT>
</TR>
<TR>
<TD align="center"><INPUT TYPE="text" NAME="cost" VALUE="19.95" SIZE=10>
<TD align="center"><INPUT TYPE="text" NAME="tax" VALUE=".06" SIZE=10>
</TR>
</TABLE>
<BR>
<TABLE BORDER=1 WIDTH=600 CELLPADDING=3>
<TR>
<TD align="center"><FONT SIZE=+1><STRONG>Unformatted Tax</STRONG></FONT>
<TD align="center"><FONT SIZE=+1><STRONG>Formatted Tax</STRONG></FONT>
<TD align="center"><FONT SIZE=+1><STRONG>TOTAL COST</STRONG></FONT>
</TR>
<TR>
<TD align="center"><INPUT TYPE="text" NAME="unformatted_tax" SIZE=15>
<TD align="center"><INPUT TYPE="text" NAME="formatted_tax" SIZE=15>
<TD align="center"><INPUT TYPE="text" NAME="total_cost" SIZE=15>
</TR>
</TABLE>
<BR>
<TABLE BORDER=0 WIDTH=400 CELLPADDING=5>
<TR>
<TD align="center"><INPUT TYPE="reset" VALUE="RESET" onClick="resetIt()">
<TD align="center"><INPUT TYPE="button" VALUE="COMPUTE" onclick="compute()">
</TR>
</TABLE>
</CENTER>
As noted you need to return the total of hte Math.round - but you also need to parse the values into numbers) and then you also have to remember that the sales tax is a percentage - so it has to be divided by 100.
I have amended your logic to
a) parse the values of the inputs into numbers using parseInt()
b) resolve the math.round() issue
c) get the sales tax value by multiplying the item cost by the sales tax percentage ... itemCost * (salesTax/100)
d) add the sales tax value to the item cost ... item cost + (itemCost * (salesTax/100))...
//Function
function calculateTip() {
var itemCost = parseInt(document.getElementById("itemCost").value);
var salesTax = parseInt(document.getElementById("salesTax").value);
//enter values window
if (itemCost === "" || salesTax == "") {
window.alert("Please enter the values!");
return;
}
//calculation
var total = Math.round(itemCost + (itemCost * salesTax/100));
//display amount
document.getElementById("totalTip").style.display = "block";
document.getElementById("amount").innerHTML = total;
}
//Hide Tip Amount and call our function with a button
document.getElementById("totalTip").style.display = "none";
document.getElementById("submit").onclick = function() {
calculateTip();
};
</head>
<body id="color">
<div class="container" id="contain">
<div class="text-center">
<h1>Sales Tax Calculator</h1>
<p> Amount Before Tax?</p>
$ <input id="itemCost" type="text" placeholder="item cost">
<p>Sales Tax Percentage?</p>
<input id="salesTax" type="text" placeholder="sales tax percent"><br><br>
<button type="submit" id="submit">submit</button>
</div>
<div class="container" ID="totalTip">
<div class="text-center">
<p>Total Tip</p>
<sup>$</sup><span id="amount">0.00</span>
</div>
</div>
</div>
<script type="text/javascript" src="javascript.js"></script>
</body>
I'm making a total and subtotal table using jQuery but I get a lot of problems. The first problem, when I reload this page, the total and subtotals display NaN even though the values from the input have been entered by default.
The second problem, data in the second row and so on, still takes the price on the first row only.
What I want:
I want the total and subtotal to be calculated automatically at the
beginning and can be changed in the future.
I want each Total to
calculate the price of each row
This is my code:
$(document).ready(function () {
$counter = 1;
$('table#invoiceitems').on('keyup', '.quantity , .price',function () {
UpdateTotals(this);
});
$counter = 1;
CalculateSubTotals();
CalculateTotal();
});
function UpdateTotals(elem) {
// This will give the tr of the Element Which was changed
var $container = $(elem).parent().parent();
var quantity = $container.find('.quantity').val();
var price = $('.price').html();
var subtotal = parseInt(quantity) * parseFloat(price);
$container.find('.subtotal').text(subtotal.toFixed(2));
CalculateTotal();
}
function CalculateSubTotals() {
// Calculate the Subtotals when page loads for the
// first time
var lineTotals = $('.subtotal');
var quantity = $('.quantity');
var price = $('.price').html();
$.each(lineTotals, function (i) {
var tot = parseInt($(quantity[i]).val()) * parseFloat($(price[i]).val());
$(lineTotals[i]).text(tot.toFixed(2));
});
}
function CalculateTotal() {
// This will Itearate thru the subtotals and
// claculate the grandTotal and Quantity here
var lineTotals = $('.subtotal');
var quantityTotal = $('.quantity');
var grandTotal = 0.0;
var totalQuantity = 0;
$.each(lineTotals, function (i) {
grandTotal += parseFloat($(lineTotals[i]).text());
totalQuantity += parseInt($(quantityTotal[i]).val())
});
$('.totalquantity').text(totalQuantity);
$('.grandtotal').text(parseFloat(grandTotal).toFixed(2));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1" id="invoiceitems">
<thead>
<tr>
<td><strong>Paper</strong>
</td>
<td><strong>Price</strong>
</td>
<td><strong>Quantity</strong>
</td>
<td><strong>Total</strong>
</td>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="3"><strong>SUBTOTAL</strong>
</td>
<td>
<label class="grandtotal"></label>
</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>
Glossy Paper A5
</td>
<td>
<span class="price">15000</span>
</td>
<td>
<input type="text" name="item[1][quantity]" class="quantity" value="1"/>
</td>
<td>
<label class="subtotal"></label>
</td>
</tr>
<tr>
<td>
Glossy Paper A5
</td>
<td>
<span class="price">20000</span>
</td>
<td>
<input type="text" name="item[1][quantity]" class="quantity" value="1"/>
</td>
<td>
<label class="subtotal"></label>
</td>
</tr>
</tbody>
</table>
Inside CalculateSubTotals, price is a string:
var price = $('.price').html();
so
$(price[i]).val()
doesn't make sense - it's a plain string already, and can't be meaningfully wrapped in jQuery.
If you want to access individual .price elements, then use just $('.price').
Also, the .prices are spans, not inputs - to get the text in a span, you should use .text(). Only use .val() to get text from input-like elements, such as from input and textarea:
var price = $('.price');
// ...
var tot = parseInt($(quantity[i]).val()) * parseFloat($(price[i]).text());
// ^^^^^^^
The same fix needs to be made to your UpdateTotals function.
$(document).ready(function() {
$counter = 1;
$('table#invoiceitems').on('keyup', '.quantity , .price', function() {
UpdateTotals(this);
});
$counter = 1;
CalculateSubTotals();
CalculateTotal();
});
function UpdateTotals(elem) {
// This will give the tr of the Element Which was changed
var $container = $(elem).parent().parent();
var quantity = $container.find('.quantity').val();
var price = $container.find('.price').text();
var subtotal = parseInt(quantity) * parseFloat(price);
$container.find('.subtotal').text(subtotal.toFixed(2));
CalculateTotal();
}
function CalculateSubTotals() {
// Calculate the Subtotals when page loads for the
// first time
var lineTotals = $('.subtotal');
var quantity = $('.quantity');
var price = $('.price');
$.each(lineTotals, function(i) {
var tot = parseInt($(quantity[i]).val()) * parseFloat($(price[i]).text());
$(lineTotals[i]).text(tot.toFixed(2));
});
}
function CalculateTotal() {
// This will Itearate thru the subtotals and
// claculate the grandTotal and Quantity here
var lineTotals = $('.subtotal');
var quantityTotal = $('.quantity');
var grandTotal = 0.0;
var totalQuantity = 0;
$.each(lineTotals, function(i) {
grandTotal += parseFloat($(lineTotals[i]).text());
totalQuantity += parseInt($(quantityTotal[i]).val())
});
$('.totalquantity').text(totalQuantity);
$('.grandtotal').text(parseFloat(grandTotal).toFixed(2));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1" id="invoiceitems">
<thead>
<tr>
<td><strong>Paper</strong>
</td>
<td><strong>Price</strong>
</td>
<td><strong>Quantity</strong>
</td>
<td><strong>Total</strong>
</td>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="3"><strong>SUBTOTAL</strong>
</td>
<td>
<label class="grandtotal"></label>
</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>
Glossy Paper A5
</td>
<td>
<span class="price">15000</span>
</td>
<td>
<input type="text" name="item[1][quantity]" class="quantity" value="1" />
</td>
<td>
<label class="subtotal"></label>
</td>
</tr>
<tr>
<td>
Glossy Paper A5
</td>
<td>
<span class="price">20000</span>
</td>
<td>
<input type="text" name="item[1][quantity]" class="quantity" value="1" />
</td>
<td>
<label class="subtotal"></label>
</td>
</tr>
</tbody>
</table>
The problem is, You already got content of price in line var price = $('.price').html(); Then why are you trying to get value in this line $(price[i]).val() ?
There is no value key to get, And input fields only have value attribute.
Solution is,
var price = $('.price');
AND
var tot = parseInt($(quantity[i]).val()) * parseFloat($(price[i]).text());
$(document).ready(function () {
$counter = 1;
$('table#invoiceitems').on('keyup', '.quantity , .price',function () {
UpdateTotals(this);
});
$counter = 1;
CalculateSubTotals();
CalculateTotal();
});
function UpdateTotals(elem) {
// This will give the tr of the Element Which was changed
var $container = $(elem).parent().parent();
var quantity = $container.find('.quantity').val();
var price = $('.price').html();
var subtotal = parseInt(quantity) * parseFloat(price);
$container.find('.subtotal').text(subtotal.toFixed(2));
CalculateTotal();
}
function CalculateSubTotals() {
// Calculate the Subtotals when page loads for the
// first time
var lineTotals = $('.subtotal');
var quantity = $('.quantity');
var price = $('.price');
$.each(lineTotals, function (i) {
var tot = parseInt($(quantity[i]).val()) * parseFloat($(price[i]).text());
$(lineTotals[i]).text(tot.toFixed(2));
});
}
function CalculateTotal() {
// This will Itearate thru the subtotals and
// claculate the grandTotal and Quantity here
var lineTotals = $('.subtotal');
var quantityTotal = $('.quantity');
var grandTotal = 0.0;
var totalQuantity = 0;
$.each(lineTotals, function (i) {
grandTotal += parseFloat($(lineTotals[i]).text());
totalQuantity += parseInt($(quantityTotal[i]).val())
});
$('.totalquantity').text(totalQuantity);
$('.grandtotal').text(parseFloat(grandTotal).toFixed(2));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1" id="invoiceitems">
<thead>
<tr>
<td><strong>Paper</strong>
</td>
<td><strong>Price</strong>
</td>
<td><strong>Quantity</strong>
</td>
<td><strong>Total</strong>
</td>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="3"><strong>SUBTOTAL</strong>
</td>
<td>
<label class="grandtotal"></label>
</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>
Glossy Paper A5
</td>
<td>
<span class="price">15000</span>
</td>
<td>
<input type="text" name="item[1][quantity]" class="quantity" value="1"/>
</td>
<td>
<label class="subtotal"></label>
</td>
</tr>
<tr>
<td>
Glossy Paper A5
</td>
<td>
<span class="price">20000</span>
</td>
<td>
<input type="text" name="item[1][quantity]" class="quantity" value="1"/>
</td>
<td>
<label class="subtotal"></label>
</td>
</tr>
</tbody>
</table>
I am trying to do a form, when you click on checkbox it has to enables the rows of the form, but it's not working...
For example, there's a checkbox above the by clicking it, it has to enable the rest of rows
I'll appreciate any help,
Thanks in advance.
Here is what I have:
<HTML>
<HEAD>
<TITLE>Online Shopping</TITLE>
<SCRIPT>
//Variables Globales
var RowsInForm = 4
var ProductsInList = 4
var SalesTaxRate = 0.12
var TaxableState = "IVA(12%)"
var ProdSubscript = 0
function MakeArray(n) {
this.length = n
for (var i = 1; i<= n; i++) {
this[i] = 0
}
return this
}
function BuildZeroArray(n) {
this.length = n
for (var i = 0; i<= n; i++) {
this[i] = 0
}
return this
}
function prodobj(name, unitprice) {
this.name = name
this.unitprice = unitprice
}
function ordobj(prodsub, qty, unitprice, extprice) {
this.prodsub = prodsub
this.qty = qty
this.unitprice = unitprice
this.extprice = extprice
}
function strToZero(anyval) {
anyval = ""+anyval
if (anyval.substring(0,1) < "0" || anyval.substring(0,1) > "9") {
anyval = "0"
}
return eval(anyval)
}
function updateRow(rownum){
var exec = 'ProdSubscript = document.ordform.prodchosen'+rownum+'.selectedIndex'
eval (exec)
ordData[rownum].prodsub=ProdSubscript
var exec='tempqty=document.ordform.qty'+rownum+'.value'
eval (exec)
ordData[rownum].qty = strToZero(tempqty)
ordData[rownum].unitprice=prodlist[ProdSubscript].unitprice
ordData[rownum].extprice = (ordData[rownum].qty) * ordData[rownum].unitprice
var exec = 'document.ordform.unitprice'+rownum+'.value = currencyPad(ordData['+rownum+'].unitprice,10)'
eval (exec)
var exec = 'document.ordform.extprice'+rownum+'.value = currencyPad(ordData['+rownum+'].extprice,10)'
eval (exec)
updateTotals()
}
function updateTotals() {
var subtotal = 0
for (var i=1; i<=RowsInForm; i++) {
subtotal = subtotal + ordData[i].extprice
}
document.ordform.subtotal.value = currencyPad(subtotal,10)
salestax = 0
if (document.ordform.Taxable.checked) {
salestax = SalesTaxRate * subtotal * 0.30
}
document.ordform.salestax.value = currencyPad(salestax,10)
document.ordform.grandtotal.value = currencyPad(subtotal+salestax,10)
}
function copyAddress() {
document.ordform.ShipName.value = document.ordform.billName.value
document.ordform.ShipCompany.value = document.ordform.billCompany.value
document.ordform.ShipAdd1.value = document.ordform.billAdd1.value
document.ordform.ShipAdd2.value = document.ordform.billAdd2.value
document.ordform.ShipCSZ.value = document.ordform.billCSZ.value
}
function currencyPad(anynum,width) {
//returns number as string in $xxx,xxx.xx format.
anynum = "" + eval(anynum)
//evaluate (in case an expression sent)
intnum = parseInt(anynum)
//isolate integer portion
intstr = ""+intnum
//add comma in thousands place.
if (intnum >= 1000) {
intlen = intstr.length
temp1=parseInt(""+(intnum/1000))
temp2=intstr.substring(intlen-3,intlen)
intstr = temp1+","+temp2
}
if (intnum >= 1000000) {
intlen = intstr.length
temp1=parseInt(""+(intnum/1000000))
temp2=intstr.substring(intlen-7,intlen)
intstr = temp1+","+temp2
}
decnum = Math.abs(parseFloat(anynum)-parseInt(anynum)) //isolate decimal portion
decnum = decnum * 100 // multiply decimal portion by 100.
decstr = "" + Math.abs(Math.round(decnum))
while (decstr.length < 2) {
decstr += "0"
}
retval = intstr + "." + decstr
if (intnum < 0) {
retval=retval.substring(1,retval.length)
retval="("+retval+")"
}
retval = "BsF"+retval
while (retval.length < width){
retval=" "+retval
}
return retval
}
</SCRIPT>
</HEAD>
<BODY aLink=#8a8a8a bgColor=#ffffff
link=#ff0000 text=#000000 vLink=#215e21>
<H3 align=center><FONT color=#0000ff><FONT size=+1></FONT></FONT></H3>
<P><BR>
<SCRIPT>
//Create a new array named prodlist with six elements.
prodlist = new BuildZeroArray(ProductsInList) //Refers to global variable ProductsInList
//Populate that array with this product info.
//The first item, prodlist[0] must be a "non-product" with
//a unitprice of zero.
prodlist[0] = new prodobj('-none-',0)
prodlist[1] = new prodobj('Apple iPhone ',5200)
prodlist[2] = new prodobj('Pc Laptop',3520)
prodlist[3] = new prodobj('Impresora',4790)
prodlist[4] = new prodobj('TV',8650)
//Create a new array, named ordData, that contains empty Order Objects.
ordData = new MakeArray(RowsInForm)
for (var i=1; i<= RowsInForm; i++) {
ordData[i] = new ordobj(0,0,0,0)}
</SCRIPT>
<FORM name=ordform></P>
<CENTER>
<P><! Display the table header></P></CENTER>
<TABLE align=center border=1>
<CENTER>
<TBODY>
<TR>
<TH width=192>
<CENTER><B>Product</B></CENTER></TH>
<TH width=72>
<CENTER><B>Qty</B></CENTER></TH>
<TH width=120>
<CENTER><B>Unit Price</B></CENTER></TH>
<TH width=120>
<CENTER><B>Ext Price</B></CENTER></TH>
<P><INPUT type=checkbox value=true>
<SCRIPT>
for (var rownum = 1;rownum <= RowsInForm; rownum++) {
document.write('<TR><TD WIDTH=192>')
document.write('<SELECT NAME="prodchosen'+rownum+'" onChange= "updateRow('+rownum+')">')
for (i = 0; i <= ProductsInList; i++) {
document.write ("<OPTION>"+prodlist[i].name)
} document.write ('</SELECT>')
document.write ('</TD><TD WIDTH=72><CENTER><INPUT NAME="qty'+rownum+'" VALUE=""')
document.write ('MAXLENGTH="3" SIZE=3 onChange="updateRow('+rownum+')"></CENTER>')
document.write ('</TD><TD WIDTH=120><CENTER>')
document.write ('<INPUT NAME="unitprice'+rownum+'" VALUE="" MAXLENGTH="10"')
document.write ('SIZE=10 onfocus="this.blur()"></CENTER>')
document.write ('</TD><TD WIDTH=120><CENTER>')
document.write ('<INPUT NAME="extprice'+rownum+'" VALUE="" MAXLENGTH="10"')
document.write ('SIZE=10 onfocus = "this.blur()"></CENTER>')
document.write ('</TD></TR>')
}
</SCRIPT>
<P></P></CENTER></TBODY></TABLE>
<CENTER>
<P><! Second table holds subtotal, sales tax, grand total></P></CENTER>
<TABLE>
<TBODY>
<TR>
<TD width=264></TD>
<TD width=120>
<CENTER>
<P>Subtotal: </P></CENTER></TD>
<TD width=120>
<CENTER>
<P><INPUT maxLength=10 name=subtotal onfocus=this.blur()
size=10></P></CENTER></TD></TR>
<TR>
<TD width=264>
<P><INPUT name=Taxable onclick=updateTotals() type=checkbox value=true>
<SCRIPT>
document.write(TaxableState)
</SCRIPT>
</P></TD>
<TD width=120>
<CENTER>
<P>IVA:</P></CENTER></TD>
<TD width=120>
<CENTER>
<P><INPUT maxLength=10 name=salestax onfocus=this.blur()
size=10></P></CENTER></TD></TR>
<TR>
<TD width=264>
<TD width=120>
<CENTER>
<P>Total: </P></CENTER></TD>
<TD width=120>
<CENTER>
<P><INPUT maxLength=10 name=grandtotal onfocus=this.blur()
size=10></P></CENTER></TD></TR></TBODY></TABLE>
<!--<P><B>Bill To:</B> <! Onto Bill To and Ship To address portions of the form></P>
<TABLE align=center border=1>
<TBODY>
<TR>
<TD width=120>
<P>Name:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=billName size=50></P></TD></TR>
<TR>
<TD width=120>
<P>Company:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=billCompany size=50> </P></TD></TR>
<TR>
<TD width=120>
<P>Address1:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=billAdd1 size=50></P></TD></TR>
<TR>
<TD width=120>
<P>Address2:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=billAdd2 size=50> </P></TD></TR>
<TR>
<TD width=120>
<P>City, State, Zip:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=billCSZ size=50></P></TD></TR>
<TR>
<TD width=120>
<P>Phone:</P></TD>
<TD width=408>
<P><INPUT maxLength=25 name=Phone size=25></P></TD></TR>
<TR>
<TD width=120>
<P>Email address:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=email size=40></P></TD></TR></TBODY></TABLE>
<CENTER>
<P><INPUT onclick=copyAddress() type=button value="Copy 'Bill To' info to 'Ship To' blanks">
</P></CENTER>
<P><B>Ship To:</B> </P>
<TABLE align=center border=1>
<TBODY>
<TR>
<TD width=120>
<P>Name:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=ShipName size=50></P></TD></TR>
<TR>
<TD width=120>
<P>Company:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=ShipCompany size=50></P></TD></TR>
<TR>
<TD width=120>
<P>Address1:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=ShipAdd1 size=50></P></TD></TR>
<TR>
<TD width=120>
<P>Address2:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=ShipAdd2 size=50></P></TD></TR>
<TR>
<TD width=120>
<P>City, State, Zip:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=ShipCSZ size=50></P></TD></TR></TBODY></TABLE>
<P><! In real life, you'd want to omit the whole onclick... thing in the input tag below. ><! Which is to say you want to get rid of... ><! onClick = "alert('I do not really get submitted anywhere. But thanks for trying me!')" ><INPUT onclick="alert('I do not really get submitted anywhere. But thanks for trying me!')" type=submit value=Submit>
<INPUT type=reset value=Reset> <! In real life, you can omit the entire input tag (i.e. the entire line) below ><INPUT onclick="self.location = 'jsindex.htm'" type=button value="All Done">
</FORM></P>-->
</body>
</html>
I have a problem with the following JavaScript code. It has an error alert said that table value is undefined. I'm trying to update the subtotal in each row by calculate price * qty.
function updateSubtotal() {
var subTotal = 0;
var tables = document.getElementsByTagName("table").rows;
var r = this.parentNode.parentNode.rowIndex;
var j = document.getElementsByTagName(".price").cellIndex;
var s = document.getElementsByTagName(".subtotal").cellIndex;
var price = tables[r].cells[j].value;
var quantity = document.getElementsByTagName("input").value;
var subAmount = price * quantity;
subTotal += Number(subAmount);
// set total for the row
document.getElementsByTagName('table').rows[r].cells[s].innerHTML = '$' + subTotal.toFixed(2);
}
updateTotal();
}
The original code that I tried to update:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
window.onload = setupCart;
function setupCart() {
var qtyInputs = document.querySelectorAll( 'input' );
for ( var i = 0; i < qtyInputs.length; i++ ) {
qtyInputs[ i ].oninput = updateSubtotal;
}
updateTotal();
}
function updateTotal() {
var total = 0;
var subTotals = document.querySelectorAll( '.subtotal' );
for ( var i = 0; i < subTotals.length; i++ ) {
var amount = subTotals[ i ].innerHTML.match( /[0-9]+.[0-9]+/ );
total += Number( amount );
}
document.querySelector( '#total' ).innerHTML = '$' + total.toFixed( 2 );
}
</script>
</head>
<body>
><table>
><tr>
><th>Description</th>
><th>Each</th>
><th>Qty</th>
><th>subtotal</th>
></tr>
<tr class="item">
<td class="description"><img src="red-shirt.jpg" alt="" />Red Crew Neck T-Shirt</td>
<td class="price">$15.00</td>
<td><input type="number" value="1" min="0" /></td>
<td class="subtotal">$15.00</td>
</tr>
<tr class="item">
<td class="description"><img src="tropical-shirt.jpg" alt="" />Blue Tropical Floral Print T-Shirt</td>
<td class="price">$25.00</td>
<td><input type="number" value="1" min="0" /></td>
<td class="subtotal">$25.00</td>
</tr>
<tr class="item">
<td class="description"><img src="black-sneakers.jpg" alt="" />Black Canvas Lace Up Sneakers</td>
<td class="price">$35.00</td>
<td><input type="number" value="1" min="0" /></td>
<td class="subtotal">$35.00</td>
</tr>
<tr class="item">
<td class="description"><img src="black-grey-jacket.jpg" alt="" />Black and Grey Hooded Jacket</td>
<td class="price">$40.00</td>
<td><input type="number" value="1" min="0" /></td>
<td class="subtotal">$40.00</td>
</tr>
<tr class="item">
<td class="description"><img src="black-sunglasses.jpg" alt="" />Black Retro Sunglasses</td>
<td class="price">$15.00</td>
<td><input type="number" value="1" min="0" /></td>
<td class="subtotal">$15.00</td>
</tr>
<tr class="cart-summary">
<td></td>
<td></td>
<th>Total:</th>
<td id="total"></td>
</tr>
</table>
</body>
</html>
The .getElementsByTagName() function returns a NodeList object. If you want the first <table> on the page, you'd use
document.getElementsByTagName("table")[0].rows ...
It would be better to fetch it just once at the start of the function:
var table = document.getElementsByTagName("table")[0];
to avoid having to re-traverse the DOM.
Maybe it's because document.getElementsByTagName doesn't return an element but a list of elements... you have to access the node you need like this document.getElementsByTagName("table")[0].rows
After an ajax call, results is returned in success, then:
var the_data = results;
var buildHTML = [];
buildHTML.push("<tr><td>Department</td><td>Count</td><td>Value</td>");
for (var i = 0; i < the_data.length; i++) {
buildHTML.push("<tr><td>" + the_data[i].department + "</td><td>" + the_data[i].count + "</td><td>£" + the_data[i].value + "</td>");
}
$('.portlet-content').empty().append("<table>" + buildHTML.join('</tr>') + "</table>");
Which builds something like:
<table>
<tr>
<td>
Department
</td>
<td>
Count
</td>
<td>
Value
</td>
</tr>
<tr>
<td>
Marketing
</td>
<td>
10
</td>
<td>
£100,000
</td>
</tr>
<tr>
<td>
Information Technology
</td>
<td>
20
</td>
<td>
£1,000,000
</td>
</tr>
</table>
I know how to add another final row at the bottom of this table, but in that row, I want to display totals, i.e. a total of the count and a total of the value, e.g:
<table>
<tr>
<td>
Department
</td>
<td>
Count
</td>
<td>
Value
</td>
</tr>
<tr>
<td>
Marketing
</td>
<td>
10
</td>
<td>
£100,000
</td>
</tr>
<tr>
<td>
Information Technology
</td>
<td>
20
</td>
<td>
£1,000,000
</td>
</tr>
<tr>
<td>
Total
</td>
<td>
30
</td>
<td>
£1,100,000
</td>
</tr>
</table>
How can this be done at clientside?
Here is a generic solution that will work for any table with a tfoot and tbody:
$("table tfoot td").each(function(columnIndex) {
var totalsElement = $(this);
if (totalsElement.hasClass("sumTotal")) {
var sum = 0.0;
totalsElement.parents("table").find("tbody tr").each(function() {
sum += parseFloat($(this).children("td").eq(columnIndex).html());
});
totalsElement.html(sum);
}
});
You need to mark the computed footer cells with "sumTotal" CSS class. To keep it simple I had to remove the pound characters from the table but it works:
http://jsfiddle.net/fRdpJ/47/
You could simply amend the for loop in your code to get the sums.
...
// vars for sum
var the_count = 0, the_sum = 0;
for (var i = 0; i < the_data.length; i++) {
the_count += the_data[i].count;
the_sum += the_data[i].value;
buildHTML.push("<tr><td>" + the_data[i].department + "</td><td>" + the_data[i].count + "</td><td>£" + the_data[i].value + "</td>");
}
buildHTML.push("<tr><td>Total</td><td>" + the_count + "</td><td>" + the_sum + "</td>");
...
add a class="Count" on the TD for which you want to calculate count and then calculate count using JQuery like this:
http://jsfiddle.net/sv2dg/13/