Code:
<html>
<head>
<script type="text/javascript">
/* <![CDATA[ */
var prices = [1.25,0.15,50,25,35];
var sprices = [1,2,3];
function $(id){
return document.getElementById(id);
}
function calc(){
var tmp = 0;
for(var i = 1; i <= prices.length; i++){
var a = parseInt($('p'+i).value);
tmp += (isNaN(a)?0:a) * prices[i-1];
}
return tmp;
}
function update(){
$('total').value ='$'+calc();
}
function validateInput(keyPressEvent){
if (navigator.appName == "Microsoft Internet Explorer")
var enteredKey = keyPressEvent.keyCode;
else if (navigator.appName == "Netscape")
var enteredKey = keyPressEvent.charCode;
var enteredChar = String.fromCharCode(enteredKey);
var retValue = true;
try{
if (!/\d/.test(enteredChar) && !/\W/.test(enteredChar))
throw "You did not enter a numeric value.";
}
catch(inputError) {
window.alert(inputError);
retValue = false;
}
finally {
return retValue;
}
}
function checkForNumber(fieldValue) {
var numberCheck = isNaN(fieldValue);
if (numberCheck == true) {
window.alert("You must enter a numeric value!");
return false;}
}
function calGrandTotal() {
var tmp = calc();
tmp += sprices[$('sel').value];
$('gtotal').value = tmp;
}
/* ]]> */
</script>
</head>
<body>
<form name="productForm" action="FormProcessor.html" method="get" enctype="application/x-www-form-urlencoded"
onsubmit="return confirmSubmit();"
onreset="return confirmReset();">
<table border="0">
<tr><td>Product 1</td><td><input id="p1" type="text" onkeypress="return validateInput(event)" onblur="update();" /> ($1.25)</td></tr>
<tr><td>Product 2</td><td><input id="p2" type="text" onkeypress="return validateInput(event)" onblur="update();" /> (.15)</td></tr>
<tr><td>Product 3</td><td><input id="p3" type="text" onkeypress="return validateInput(event)" onblur="update();" /> ($50)</td></tr>
<tr><td>Product 4</td><td><input id="p4" type="text" onkeypress="return validateInput(event)" onblur="update();" /> ($25)</td></tr>
<tr><td>Product 5</td><td><input id="p5" type="text" onkeypress="return validateInput(event)" onblur="update();" /> ($35)</td></tr>
<tr><td>Total</td><td><input id="total" type="text" onkeypress="return validateInput(event)" onfocus="update();" /> </td></tr>
<tr><td>Shipping Info</td><td>
<select name="shippingMethod" id='sel'>
<option selected="selected" value="0">Standard ground UPS</option>
<option value="1">USPS</option>
<option value="2">2nd Day Air</option>
</select></td></tr>
<tr><td>Total W/ Shipping</td><td>
<input id="gtotal" type="text" style="height: 22px" readonly="readonly" />
<input name="shipTotalB" type="button" value="Calculate Total with shipping" onclick="calGrandTotal()" /></td></tr>
</table>
Reply With Quote
</html>
I tried to follow your "code".
Some suggestion, everything IMHO:
1) I'd use id instead of names
2) Use document.getElementById function
3) Remeber that this refers to the object which called the code: if you use this as an argument of onclick event, refered to a button, this would refear to that button,not to grandtotal.
Bookmarks