All this is a little bit over my experience but I have looked everywhere I could, and researched this stuff for 6 hours so far today and am just running into brick walls.
I have a table, where a user enters two variables and from those two variables 12 different numbers are spit out.
The problem those numbers are spit out as plain text strings into readonly text fields, and I need them to be displayed as (US) currency.
All of the input fields in the table are using onchange to run the first function which does the calculations, but the second and third functions which I found online I can not get to run.
HTML:
<form name="form" >
<table width="550" border="0">
<tr>
<td width="265" height="30"><div align="right">Number of Business Customers</div></td>
</tr>
<TR>
<td width="265" height="30"><div align="right">Number of Business Clients:</div></td>
<td width="142" div align="center"><input style="font-size:12px;text-align:center;" name="sum1" onChange="updatesum();CurrencyFormatted();CommaFormatted90;" /></td>
<td width="129" div align="center"> </td>
</tr>
<TR>
<td height="30"><div align="right">Average Number of Employees:</td>
<TD div align="center"><input style="font-size:12px;text-align:center;" name="sum2" onChange="updatesum();CurrencyFormatted();CommaFormatted();" /></TD>
<TD div align="center"> </TD>
<TR>
<td height="30"><div align="right">Anticipated Employee Tax Reduction:</div></td>
<TD div align="center"><input style="font-size:12px;text-align:center;border:none;" name="sum16" readonly "></TD>
<TD div align="center"><input style="font-size:12px;text-align:center;border:none" name="sum26" readonly><BR /></TD>
</TR>
<TR>
<td height="30"><div align="right">Potential Payroll Tax Reduction (annually):</div></td>
<TD div align="center"><input style="font-size:12px;text-align:center;border:none" name="sum17" readonly ></TD>
<TD div align="center"><input style="font-size:12px;text-align:center;border:none" name="sum27" readonly ></TD>
</TR>
<TR>
<td height="30"><div align="right">Potential Payroll Tax Reduction (monthly):</td>
<TD div align="center"><input type="text" style="font-size:12px;text-align:center;border:none" name="sum18" readonly ></td>
<TD div align="center"><input style="font-size:12px;text-align:center;border:none" name="sum28" readonly ></td>
</TR>
<TR>
<td height="30"><div align="right">Pearl Logic Billing (50% of savings, for 12 months):</td>
<TD div align="center"><input style="font-size:12px;text-align:center;border:none" name="sum19" readonly ></td>
<TD div align="center"><input style="font-size:12px;text-align:center;border:none" name="sum29" readonly ></td>
</TR>
<TR>
<td height="30"><div align="right">Sales Agent Monthly Comp (8%):</td>
<TD div align="center"><input style="font-size:12px;text-align:center;border:none" name="sum14" readonly ></td>
<TD div align="center"><input style="font-size:12px;text-align:center;border:none" name="sum24" readonly ></td>
</TR>
<TR>
<td height="30"><div align="right">Sales Agent Total Comp (8%):</td>
<TD div align="center"><input style="font-size:12px;text-align:center;border:none" name="sum15" readonly ></td>
<TD div align="center"><input style="font-size:12px;text-align:center;border:none" name="sum25" readonly ></td>
</TR>
</table>
</form>
Javascript:
function updatesum() {
document.form.sum14.value = ((((((document.form.sum1.value -0)*(document.form.sum2.value -0)*300))/12)/2)*.08);
document.form.sum24.value = ((((((document.form.sum1.value -0)*(document.form.sum2.value -0)*400))/12)/2)*.08);
document.form.sum15.value = (((((((document.form.sum1.value -0)*(document.form.sum2.value -0)*300))/12)/2)*.08)*12);
document.form.sum25.value = (((((((document.form.sum1.value -0)*(document.form.sum2.value -0)*400))/12)/2)*.08)*12);
document.form.sum16.value = 300;
document.form.sum26.value = 400;
document.form.sum17.value = ((document.form.sum1.value -0)*(document.form.sum2.value -0)*300);
document.form.sum27.value = ((document.form.sum1.value -0)*(document.form.sum2.value -0)*400);
document.form.sum18.value = (((document.form.sum1.value -0)*(document.form.sum2.value -0)*300)/12);
document.form.sum28.value = (((document.form.sum1.value -0)*(document.form.sum2.value -0)*400)/12);
document.form.sum19.value = ((((document.form.sum1.value -0)*(document.form.sum2.value -0)*300)/12)/2);
document.form.sum29.value = ((((document.form.sum1.value -0)*(document.form.sum2.value -0)*400)/12)/2);
}
//--></script>
<script type="text/javascript"><!--
function CurrencyFormatted()
{
var i = parseFloat(amount);
if(isNaN(i)) { i = 0.00; }
var minus = '';
if(i < 0) { minus = '-'; }
i = Math.abs(i);
i = parseInt((i + .005) * 100);
i = i / 100;
s = new String(i);
if(s.indexOf('.') < 0) { s += '.00'; }
if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
s = minus + s;
return s;
}
//--></script>
<script type="text/javascript"><!--
function CommaFormatted()
{
var delimiter = ","; // replace comma if desired
var a = amount.split('.',2)
var d = a[1];
var i = parseInt(a[0]);
if(isNaN(i)) { return ''; }
var minus = '';
if(i < 0) { minus = '-'; }
i = Math.abs(i);
var n = new String(i);
var a = [];
while(n.length > 3)
{
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if(n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
if(d.length < 1) { amount = n; }
else { amount = n + '.' + d; }
amount = minus + amount;
return amount;
}
//--></script>
Your functions have an undefined amount variable. Presumably they just crash with an error.
First you need to remove those function calls from the onChange listener.
Second, change the functions to take an unformatted value and return a formatted one
function CurrencyFormatted(amount) { //<-- notice the method parameter
var i = parseFloat(amount);
if(isNaN(i)) { i = 0.00; }
var minus = '';
if(i < 0) { minus = '-'; }
i = Math.abs(i);
i = parseInt((i + .005) * 100);
i = i / 100;
s = new String(i);
if(s.indexOf('.') < 0) { s += '.00'; }
if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
s = minus + s;
return s;
}
Now change each of your set calls in your updatesum to first format the value
var sum14 = ((((((document.form.sum1.value -0)*(document.form.sum2.value -0)*300))/12)/2)*.08);
var formattedSum14 = CommaFormatted(CurrencyFormatted(sum14));
document.form.sum14.value = sum14;
Related
I am in the process of writing a webpage. I have everything done that is needed, however, when you enter any quantity over 30 it will make the id = "shipping" color red. It does this but it does it for anything less than 30 as well. Also I am having trouble with my submit button sending off to a server/url. Any help is appreciated! I will attach my code!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> Widgets R' Us </title>
<style>
table,
td {
border: 1px solid black;
}
</style>
<script type="text/javascript">
//Check if non -number or a negative number
function realNumber() {
var qty1 = document.getElementById("Quantity1").value;
var qty2 = document.getElementById("Quantity2").value;
var qty3 = document.getElementById("Quantity3").value;
//isNaN is a predetermined function
if ((isNaN(qty1) || qty1 < 0) || (isNaN(qty2) || qty2 < 0) || (isNaN(qty3) || qty3 < 0)) {
alert("The quantity given is not a real number or is a negative number!");
return false; //Will not allow for data to go to server.
} else {
return true;
}
}
function total() {
var p1 = document.getElementById("Price1").value; //Value is referenced to the input tag
var p2 = document.getElementById("Price2").value;
var p3 = document.getElementById("Price3").value;
var qty1 = document.getElementById("Quantity1").value;
var qty2 = document.getElementById("Quantity2").value;
var qty3 = document.getElementById("Quantity3").value;
var over = qty1 + qty2 + qty3;
if (realNumber()) {
var totals = (p1 * qty1) + (p2 * qty2) + (p3 * qty3);
var yes = (totals).toFixed(2);
document.getElementById("ProductTotal").innerHTML = "$" + yes;
if (over > 30) {
document.getElementById("shipping").style.color = "red";
} else {
document.getElementById("shipping").style.color = "black";
}
}
}
function checkOut() {
if (total()) {
if ((document.getElementById("shipping").style.color == "red") &&
(document.getElementById("extra").checked)) {
return true;
}
}
return false;
}
</script>
</head>
<body>
<div>
<h1><b><big> Widgets R' Us </b></strong>
</h1>
<h2><b> Order/Checkout </b></h2>
<form name "widgets" onsubmit="return checkOut();" action="https://www.reddit.com/" method="get">
<div id="mainTable">
<table>
<tr>
<td>Widget Model:</td>
<td>37AX-L
<td>
</tr>
<tr>
<td>Price per Unit:</td>
<td>$12.45 <input type="hidden" id="Price1" name="Price1" value="12.45" /</td>
</tr>
<tr>
<td>State:</td>
<td>Regular</td>
</tr>
<tr>
<td>Quantity:</td>
<td> <input type="text" id="Quantity1" name="Quantity1" value="0" /</td>
</tr>
</table>
<tr>
<td> </td>
<td> </td>
</tr>
<table>
<tr>
<td>Widget Model:</td>
<td>42XR-J</td>
</tr>
<tr>
<td>Price per Unit:</td>
<td>$15.34 <input type="hidden" id="Price2" name="Price2" value="15.34" /></td>
</tr>
<tr>
<td>State:</td>
<td>Regular</td>
</tr>
<tr>
<td>Quantity:</td>
<td> <input type="text" id="Quantity2" name="Quantity2" value="0" /></td>
</tr>
</table>
<tr>
<td> </td>
<td> </td>
</tr>
<table>
<tr>
<td>Widget Model:</td>
<td>93ZZ-A</td>
</tr>
<tr>
<td>Price per Unit:</td>
<td>$28.99 <input type="hidden" id="Price3" name="Price3" value="28.99" /></td>
</tr>
<tr>
<td>State:</td>
<td>Regular</td>
</tr>
<tr>
<td>Quantity:</td>
<td> <input type="text" id="Quantity3" name="Quantity3" value="0" /></td>
</tr>
</table>
<tr>
<td> </td>
<td> </td>
</tr>
<table>
<tr>
<td>Product Total:</td>
<td>
<p id="ProductTotal"> 0 </p>
</td>
</tr>
<tr>
<td> <input type="checkbox" id="extra" name="extra"> </td>
<td>
<p id="shipping">If the quantity exceeds 30 units, there will be extra shipping!</p>
</td>
</tr>
</table>
</div>
<tr>
<td> <input type="Submit" value="Submit" /> </td>
<td> <input type="button" value="Calculate" onClick="total()" /> </td>
</tr>
</form>
</body>
</html>
Problem with your values qty1,qty2,qty3. these values are reading as string. so instead of addding these values , its concatinating the strings. replace
var qty1 = document.getElementById("Quantity1").value;
var qty2 = document.getElementById("Quantity2").value;
var qty3 = document.getElementById("Quantity3").value;
with
var qty1 = parseInt(document.getElementById("Quantity1").value);
var qty2 = parseInt(document.getElementById("Quantity2").value);
var qty3 = parseInt(document.getElementById("Quantity3").value);
It will Solve your problem with 'Red'.
For the submit button, function total() is not returning anything. so change something like
function total() {
var p1 = document.getElementById("Price1").value; //Value is referenced to the input tag
var p2 = document.getElementById("Price2").value;
var p3 = document.getElementById("Price3").value;
var qty1 = parseInt(document.getElementById("Quantity1").value);
var qty2 = parseInt(document.getElementById("Quantity2").value);
var qty3 = parseInt(document.getElementById("Quantity3").value);
var over = qty1 + qty2 + qty3;
if (realNumber()) {
var totals = (p1 * qty1) + (p2 * qty2) + (p3 * qty3);
var yes = (totals).toFixed(2);
document.getElementById("ProductTotal").innerHTML = "$" + yes;
if (over > 30) {
document.getElementById("shipping").style.color = "red";
return true;
} else if(over>0) {
document.getElementById("shipping").style.color = "black";
return true;
}else{
document.getElementById("shipping").style.color = "black";
return false;
}
}
}
and checkout() as
function checkOut() {
if (total()) {
if (((document.getElementById("shipping").style.color == "red") &&
(document.getElementById("extra").checked))||
(document.getElementById("shipping").style.color != "red")) {
return true;
}
}
return false;
}
Replace
var over = qty1 + qty2 + qty3;
With
var over = parseInt(qty1) + parseInt(qty2) + parseInt(qty3);
There were some minor HTML errors but the real issue is that numeric strings were being concatenated. So, to get the quantity values you need to use parseInt() to extract the integer value so that math is performed instead of string concatenation. Also, it's a little odd that the user has to click the Calculate Button in order to see a total. The button does work correctly, but is this what you really want?
One more thing, as tempting as it may be to directly alter the color of elements with JavaScript, in terms of keeping the code more robust, it is preferable to simply change the class name as the code does in this example since I created two classes in the CSS for this purpose.
The form now submits as long as the checkbox is unchecked and the units do not exceed 30. I changed the method to "post" and adjusted the true/false return statements in checkOut(). Note when data is submitted using the POST method, then no form data appears appended to the URL; for more info see here. I also altered the totals() function so that now it returns a value, namely the total price.
var d = document;
d.g = d.getElementById;
var qty = [0, 0, 0, 0];
var shipping = d.g("shipping");
function realNumber() {
var qtyInvalid = [0, 0, 0, 0];
for (let i = 1, max = qtyInvalid.length; i < max; i++) {
qtyInvalid[i] = (isNaN(qty[i]) || qty[i] < 0);
}
if (qtyInvalid[1] || qtyInvalid[2] || qtyInvalid[3]) {
console.log("The quantity given is not a real number or is a negative number!");
return false;
}
return true;
}
function total() {
var over = 0;
var price = [0, 0, 0, 0];
for (j = 1, max = price.length; j < max; j++) {
price[j] = d.g("Price" + j + "").value;
qty[j] = d.g("Quantity" + j + "").value;
}
var totals = 0;
var yes = 0;
const radix = 10;
for (q = 1, max = qty.length; q < max; q++) {
over += parseInt(qty[q], radix)
}
//console.log(over);
if (!realNumber()) {
return false;
}
for (let k = 1, max2 = price.length; k < max2; k++) {
totals += (price[k] * qty[k]);
}
yes = (totals).toFixed(2);
d.g("ProductTotal").innerHTML = "$" + yes;
shipping.className = (over > 30) ? "red" : "black";
return totals;
} // end total
function checkOut() {
var retval = false;
var shippingIsRed = (shipping.className == "red");
var extraChecked = d.g("extra").checked;
if ( total() ) {
retval = (!shippingIsRed && !extraChecked)? true : false;
}
return retval;
} //end checkout
h1 {
font: 200% Arial, Helvetica;
font-weight: bold;
}
h2 {
font-weight: bold;
}
table,
td {
border: 1px solid black;
}
p.red {
color: #f00;
}
p.black {
color: #000;
}
<div>
<h1>Widgets R' Us</h1>
<h2>Order/Checkout</h2>
<form name="widgets" onsubmit="return checkOut()" action="https://www.example.com/" method="post">
<div id="mainTable">
<table>
<tr>
<td>Widget Model:</td>
<td>37AX-L
<td>
</tr>
<tr>
<td>Price per Unit:</td>
<td>$12.45 <input type="hidden" id="Price1" name="Price1" value="12.45" </td>
</tr>
<tr>
<td>State:</td>
<td>Regular</td>
</tr>
<tr>
<td>Quantity:</td>
<td> <input type="text" id="Quantity1" name="Quantity1" value="0" </td>
</tr>
</table>
<tr>
<td> </td>
<td> </td>
</tr>
<table>
<tr>
<td>Widget Model:</td>
<td>42XR-J</td>
</tr>
<tr>
<td>Price per Unit:</td>
<td>$15.34 <input type="hidden" id="Price2" name="Price2" value="15.34"></td>
</tr>
<tr>
<td>State:</td>
<td>Regular</td>
</tr>
<tr>
<td>Quantity:</td>
<td> <input type="text" id="Quantity2" name="Quantity2" value="0"></td>
</tr>
</table>
<tr>
<td> </td>
<td> </td>
</tr>
<table>
<tr>
<td>Widget Model:</td>
<td>93ZZ-A</td>
</tr>
<tr>
<td>Price per Unit:</td>
<td>$28.99 <input type="hidden" id="Price3" name="Price3" value="28.99"></td>
</tr>
<tr>
<td>State:</td>
<td>Regular</td>
</tr>
<tr>
<td>Quantity:</td>
<td> <input type="text" id="Quantity3" name="Quantity3" value="0"></td>
</tr>
</table>
<tr>
<td> </td>
<td> </td>
</tr>
<table>
<tr>
<td>Total Price:</td>
<td>
<p id="ProductTotal"> 0 </p>
</td>
</tr>
<tr>
<td> <input type="checkbox" id="extra" name="extra"> </td>
<td>
<p id="shipping" class="black">If the quantity exceeds 30 units, there will be extra shipping!</p>
</td>
</tr>
</table>
</div>
<tr>
<td> <input type="Submit" value="Submit" /> </td>
<td> <input type="button" value="Calculate" onClick="total()"> </td>
</tr>
</form>
I also removed some unnecessary repetitive code that fetches the quantity values, taking advantage of JavaScript closures and for-loops.
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>
Iam working on an application with certain calculations. I need to show and sum up the totals of Total INR and Margin Field. When a user put a percentage in Add (%) it calculates certain things and show the margin. And at the end script has to show the sum totals. Its showing Nan as of now.
My script is below:
<html>
<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<script type='text/javascript'>//<![CDATA[
function isNum(value)
{
return 123;
}
function calcTotals1()
{
var grandTotal = 0;
var i = 0;
while (document.forms['cart'].elements['add_percentage[]'][i])
{
add_percentageObj = document.forms['cart'].elements['add_percentage[]'][i];
addon_valueObj = document.forms['cart'].elements['addon_value[]'][i];
total_inr_valueObj = document.forms['cart'].elements['total_inr[]'][i];
totalObj = document.forms['cart'].elements['add_value[]'][i];
marginObj = document.forms['cart'].elements['margin_for[]'][i];
if (isNaN(add_percentageObj.value)) {
add_percentageObj = '';
}
if (isNaN(addon_valueObj.value)) {
addon_valueObj = '';
}
if (add_percentageObj.value != 0) {
totalObj.value = (((total_inr_valueObj.value * 1) * add_percentageObj.value / 100) + total_inr_valueObj.value * 1).toFixed(3);
grandTotal = grandTotal + parseFloat(totalObj.value);
marginObj.value = ((totalObj.value * 1) - (total_inr_valueObj.value * 1)).toFixed(3);
margin_total = ((margin_total *1) + marginObj.value * 1);
} else if (addon_valueObj.value !=0) {
totalObj.value = ((addon_valueObj.value * 1) + total_inr_valueObj.value * 1).toFixed(3);
grandTotal = grandTotal + parseFloat(totalObj.value);
marginObj.value = ((totalObj.value * 1) - (total_inr_valueObj.value * 1)).toFixed(3);
margin_total = ((margin_total *1) + marginObj.value * 1);
} else {
totalObj.value = ((addon_valueObj.value * 1) + total_inr_valueObj.value * 1).toFixed(3);
grandTotal = grandTotal + parseFloat(totalObj.value);
marginObj.value = ((totalObj.value * 1) - (total_inr_valueObj.value * 1)).toFixed(3);
margin_total = ((margin_total *1) + marginObj.value * 1);
}
i++;
}
document.getElementById('grand_total').value = grandTotal.toFixed(3);
document.getElementById('margin_total').value = margin_total.toFixed(3);
//document.getElementById('total_inr1').value = total_inr1.toFixed(3);
//document.getElementById('margin_for').value = margin_for;
return;
}
</script>
</head>
<body>
<form name="cart" class="single">
<div align="center" class="base">
<table width="100%" border=1 style="border-collapse: collapse;">
<tr bgcolor="#E6E6FA">
<td colspan="6"><b>Terms and Cost</b></td>
</tr>
<tr>
<td>Terms</td>
<td>Total INR</td>
<td>Add (%)</td>
<td>Add Value</td>
<td>Total Value</td>
<td>Margin</td>
</tr>
<tr>
<td width="25%">Export Charges</td>
<td width="75%"><input type="text" id="total_inr[]" name="total_inr[]" value="13263.984"></td>
<td><input type="text" id="add_percentage[]" name="add_percentage[]" value="" onchange="calcTotals1()"></td>
<td><input type="text" id="addon_value[]" name="addon_value[]" value="" onchange="calcTotals1()"></td>
<td><input type="text" id="add_value[]" name="add_value[]" value=""></td>
<td><input type="text" id="margin_for[]" name="margin_for[]" value=""></td>
</tr>
<tr>
<td width="25%">IATA Charges</td>
<td width="75%"><input type="text" id="total_inr[]" name="total_inr[]" value="16579.98"></td>
<td><input type="text" id="add_percentage[]" name="add_percentage[]" value="" onchange="calcTotals1()"></td>
<td><input type="text" id="addon_value[]" name="addon_value[]" value="" onchange="calcTotals1()"></td>
<td><input type="text" id="add_value[]" name="add_value[]" value=""></td>
<td><input type="text" id="margin_for[]" name="margin_for[]" value=""></td>
</tr>
<tr>
<td></td>
<td><input name="gTotal" id="grand_total" style="font-weight: bold" size="20" /></td>
<td></td>
<td></td>
<td></td>
<td><input type='text' style='font-weight: bold' id='margin_total' name='margin_total' size='8' readonly /></td>
</tr>
</table>
</div>
</form>
</body>
</html>
Try to use parseInt() to work really with integers instead of strings. If you read values from some html elements, you get these values as string. It also can cause wrong calculations. Just call parseInt() each time you read numeric value from html page element
It's part of the larger task. Why is the problem Nan and how to solve it? The table is added together elements from several pools <input> which elemenatymi table. All code is summed up in the table of size k / d.
Why is the problem Nan and how to solve it?
function licz(tableID){
var table = document.getElementById(tableID);
var k, d, s=0, temp;
var i = table.rows.length;
for(k=1; k<=i; k++){
for(d=0; d<2; d++){
temp = parseFloat(document.getElementById(tableID).rows[k].cells[d].innerHTML);
alert(temp);
s=s+temp;
}
document.getElementById(tableID).rows[k].cells[d].innerHTML = s;
}
}
<form name="roz" action="">
<table id="tyg" class="product_values" style="width: 20%" border=1>
<tr>
<td> Pon </td>
<td> Wt </td>
<td> Sum </td>
</tr><tr>
<td> <input type="number" name="inp_a" ></td>
<td> 4 </td>
<td></td>
</table>
</form>
<button onclick="licz('tyg')">go</button>
This is not right way for getting value from child elements you should do something like this :
JavaScript:
function licz(tableID){
var table = document.getElementById(tableID);
var k, d, temp;
var i = table.rows.length;
for (k = 1; k <= i; k++) {
for (d = 0; d < 2; d++) {
if (d == 0) {
temp = parseFloat(document.getElementById(tableID).rows[k].cells[d].childNodes[1].value);
}
if (d == 1) {
temp = temp + parseFloat(document.getElementById(tableID).rows[k].cells[d].innerHTML);
}
}
document.getElementById(tableID).rows[k].cells[d].innerHTML = temp;
document.getElementById('num').v
}
}
HTML:
<table id="tyg" class="product_values" style="width: 20%" border=1>
<tr>
<td> Pon </td>
<td> Wt </td>
<td> Sum </td>
</tr>
<tr>
<td> <input id = 'num' type="number" name="inp_a" ></td>
<td> 4 </td>
<td></td>
</tr>
</table>
well... it's a good question. You should read DOM for knowing more about this.
I have a table which has one row in which I multiply two fields, namely quantity and rate/quantity, to get the product total. I have provided a button to add a new row which basically clones the 1st row. Now I want the cloned row to also have the same product as the 1st row. I have tried the following code:
<!DOCTYPE html>
<html>
<h3 align="center">K J Somaiya College Of Engineering, Vidyavihar, Mumbai-400 077</h3>
<h3 align="center">Department Of Information Technology</h3>
<body>
<script>
function WO1() {
var qty = document.getElementById('qty').value;
var price = document.getElementById('price').value;
answer = (Number(qty) * Number(price)).toFixed(2);
document.getElementById('totalprice').value = answer;
}
function WO2() {
var qty = document.getElementById('qty1').value;
var price = document.getElementById('price1').value;
answer = (Number(qty) * Number(price)).toFixed(2);
document.getElementById('totalprice1').value = answer;
}
function WO3() {
var qty = document.getElementById('qty2').value;
var price = document.getElementById('price2').value;
answer = (Number(qty) * Number(price)).toFixed(2);
document.getElementById('totalprice2').value = answer;
}
</script>
<script>
function validateNumbe()
{
var x=document.getElementById("floor").value;
if (x==null || x=="")
{
alert("Floor must be entered");
return false;
}
}
function validateN()
{
var x=document.getElementById("lab").value;
if (x==null || x=="")
{
alert("Laboratory Name must be entered");
return false;
}
}
function validateNumb()
{
var x=document.getElementById("room").value;
if (x==null || x=="")
{
alert("Room No must be entered");
return false;
}
}
function validateNum()
{
var x=document.getElementById("labi").value;
if (x==null || x=="")
{
alert("Name of Laboratory Incharge must be entered");
return false;
}
}
function validateNu()
{
var x=document.getElementById("year").value;
if (x==null || x=="")
{
alert("Budget for the year must be entered");
return false;
}
}
</script>
<table width="100%" cellspacing="10">
<tr>
<td align="left">Date:<input type="date" name="date"/></td>
<td align="right">Floor: <input type="text" id="floor" onchange="validateNumbe()"
onblur="validateNumbe()"/> </td>
</tr>
<tr>
<td align="left">Laboratory Name: <input type="text" id="lab" onchange="validateN()"
onblur="validateN()"/></td>
<td align="right">Room no: <input type="text" id="room" onchange="validateNumb()"
onblur="validateNumb()"/></td>
</tr>
<tr>
<td align="left">Name of Laboratory Incharge: <input type="text" id="labi"
onchange="validateNum()" onblur="validateNum()"/></td>
<td align="right">Budget for the year: <input type="text" id="year" onchange="validateNu()"
onblur="validateNu()"/></td>
</tr>
</table>
<h3 align="left"><b>Computer</b><h3>
<table id="POITable" border="1" width="100%">
<tr>
<td style="width:10%">Sr No.</td>
<td>Item Description</td>
<td>Quantity</td>
<td>Rate(Inclusive of Taxes)</td>
<td>Total Cost</td>
</tr>
<tr>
<td>1</td>
<td><textarea rows="4" cols="50" name="comp_item"></textarea></td>
<td><input type='text' name='Quantity' id='qty' class="qty" placeholder='Qty' /></td>
<td><input type='text' name='Rate' id='price' class="price" placeholder='Price (£)'
onChange="WO1()" /></td>
<td><input type='text' name='Total' id='totalprice' class="price" placeholder='Total
Price (£)' /></td>
</tr>
</table>
<input type="button" id="addmorePOIbutton" value="Add New Row"/>
<h3 align="left"><b>Equipment</b><h3>
<table id="POITable1" border="1" width="100%">
<tr>
<th style="width:10%">Sr No.</th>
<th>Item Description</th>
<th>Quantity</th>
<th>Rate(Inclusive of Taxes)</th>
<th>Total Cost</th>
</tr>
<tr>
<td>1</td>
<td><textarea rows="4" cols="50" name="comp_item"></textarea></td>
<td><input type='text' name='Quantity' id='qty1' class="qty" placeholder='Qty' /></td>
<td><input type='text' name='Rate' id='price1' class="price" placeholder='Price (£)'
onChange="WO2()" /></td>
<td><input type='text' name='Total' id='totalprice1' class="price" placeholder='Total
Price (£)' /></td>
</tr>
</table>
<input type="button" id="addmorePOIbutton1" value="Add New Row"/>
<h3 align="left"><b>Furniture</b><h3>
<table id="POITable2" border="1" width="100%">
<tr>
<th style="width:10%">Sr No.</th>
<th>Item Description</th>
<th>Quantity</th>
<th>Rate(Inclusive of Taxes)</th>
<th>Total Cost</th>
</tr>
<tr>
<td>1</td>
<td><textarea rows="4" cols="50" name="comp_item"></textarea></td>
<td><input type='text' name='Quantity' id='qty2' class="qty" placeholder='Qty' /></td>
<td><input type='text' name='Rate' id='price2' class="price" placeholder='Price (£)'
onChange="WO3()" /></td>
<td><input type='text' name='Total' id='totalprice2' class="price" placeholder='Total
Price (£)' /></td>
</tr>
</table>
<input type="button" id="addmorePOIbutton2" value="Add New Row"/>
<script>
( function() { // Prevent vars from leaking to the global scope
var formTable = document.getElementById('POITable');
var newRowBtn = document.getElementById('addmorePOIbutton');
newRowBtn.addEventListener('click', insRow, false); //added eventlistener insetad of inline
onclick-attribute.
function insRow() {
var new_row = formTable.rows[1].cloneNode(true),
numTableRows = formTable.rows.length;
// Set the row number in the first cell of the row
new_row.cells[0].innerHTML = numTableRows;
numTableRows=numTableRows - 1;
var inp1 = new_row.cells[1].getElementsByTagName('textarea')[0];
inp1.name += numTableRows;
inp1.value = '';
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.name += numTableRows;
inp2.value = '';
var inp3 = new_row.cells[3].getElementsByTagName('input')[0];
inp3.name += numTableRows;
inp3.value = '';
var inp4 = new_row.cells[4].getElementsByTagName('input')[0];
inp4.name += numTableRows;
inp4.value = '';
// Append the new row to the table
formTable.appendChild( new_row );
}
var formTable1 = document.getElementById('POITable1');
var newRowBtn1 = document.getElementById('addmorePOIbutton1');
newRowBtn1.addEventListener('click', insRow1, false); //added eventlistener insetad of inline
onclick-attribute.
function insRow1() {
var new_row = formTable1.rows[1].cloneNode(true),
numTableRows = formTable1.rows.length;
// Set the row number in the first cell of the row
new_row.cells[0].innerHTML = numTableRows;
numTableRows=numTableRows - 1;
var inp1 = new_row.cells[1].getElementsByTagName('textarea')[0];
inp1.name += numTableRows;
inp1.value = '';
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.name += numTableRows;
inp2.value = '';
var inp3 = new_row.cells[3].getElementsByTagName('input')[0];
inp3.name += numTableRows;
inp3.value = '';
var inp4 = new_row.cells[4].getElementsByTagName('input')[0];
inp4.name += numTableRows;
inp4.value = '';
// Append the new row to the table
formTable1.appendChild( new_row );
}
var formTable2 = document.getElementById('POITable2');
var newRowBtn2 = document.getElementById('addmorePOIbutton2');
newRowBtn2.addEventListener('click', insRow2, false); //added eventlistener insetad of inline
onclick-attribute.
function insRow2() {
var new_row = formTable2.rows[1].cloneNode(true),
numTableRows = formTable2.rows.length;
// Set the row number in the first cell of the row
new_row.cells[0].innerHTML = numTableRows;
numTableRows=numTableRows - 1;
var inp1 = new_row.cells[1].getElementsByTagName('textarea')[0];
inp1.name += numTableRows;
inp1.value = '';
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.name += numTableRows;
inp2.value = '';
var inp3 = new_row.cells[3].getElementsByTagName('input')[0];
inp3.name += numTableRows;
inp3.value = '';
var inp4 = new_row.cells[4].getElementsByTagName('input')[0];
inp4.name += numTableRows;
inp4.value = '';
// Append the new row to the table
formTable2.appendChild( new_row );
}
})();
function myfun()
{
var lun= document.getElementById('POITable').rows.length;
document.getElementsByName("len")[0].value = lun-1;
var lun1= document.getElementById('POITable1').rows.length;
document.getElementsByName("len1")[0].value = lun1-1;
var lun2= document.getElementById('POITable2').rows.length;
document.getElementsByName("len2")[0].value = lun2-1;
}
function myFunction()
{
window.print();
}
</script>
<input type="hidden" name="len" value="1">
<input type="hidden" name="len1" value="1">
<input type="hidden" name="len2" value="1">
<table width="100%">
<tr>
<td><br><br><br></td>
<td><br><br><br></td>
<td><br><br><br></td>
</tr>
<tr>
<td align="left">Signature <br>Lab-In-Charge</td>
<td align="center">Signature<br>Lab Assistant</td>
<td align="right">Signature <br>Head of Department</td>
</tr>
</table>
<br><br><br>
<input type="submit" value="SUBMIT" onclick='this.form.action="archive.php";myfun();'>
<input type="submit" value="SAVE AND CONTINUE LATER"
onclick='this.form.action="myphpformhandler.php";myfun();'>
</form>
<h3 align="center"><button onclick="myFunction()"><h3>Print this page</h3></button></h3>
</body>
</html>
i have created the JSFiddle but the multiplication is not working in it.
http://jsfiddle.net/xkY4Z/2/
Not a perfect solution to your problem but a bit closer Working Fiddle
Done using jQuery
$(document).on('change','input', function () {
var id = $(this).attr('id').split("-");
var answer = (Number($('#qty-' + id[1]).val()) * Number($('#price-' + id[1]).val())).toFixed(2);
$('#totalprice-' + id[1]).val(answer);
});
Update
Working Fiddle with name
Latest
Fiddle with Grand total