How properly round a number? - javascript

I need to round or fix it somehow, so the numbers comes out properly in the form.
I have tried to use toPrecision(), but I`ve never done it before and can't find a good understandable way to use it. On the screenshot is my issue.
const priceSmall = 4.00;
const priceMedium = 5.00;
const priceLarge = 7.00;
const priceToppings = 0.50;
const pst = .07;
const gst = .07
let subtotal = 0;
////////////////Pizza size calculation///////////////
function calculateSize(element) {
if (element == null) {
return;
}
switch(element.value) {
case "10":
subtotal = priceSmall;
break;
case "12":
subtotal = priceMedium;
break;
case "15":
subtotal = priceLarge;
break;
}
recalculateTotal();
}
/////////////Topping calculation////////////
function toppingOptionPrice(element) {
if (element.checked) {
subtotal += priceToppings;
} else {
subtotal -= priceToppings;
}
recalculateTotal();
}
////////////Total//////////////
function recalculateTotal() {
let pstToPay = subtotal * pst;
let gstToPay = subtotal * gst;
let total = subtotal + pstToPay + gstToPay;
document.getElementById("subtotal").value = subtotal.toFixed(2);
document.getElementById("pstToPay").value = pstToPay.toFixed(2);
document.getElementById("gstToPay").value = gstToPay.toFixed(2);
document.getElementById("total").value = total.toFixed(2);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pizza Order Form</title>
<link rel="stylesheet" href="css/style.css">
<script src="scripts/script.js"></script>
<body>
<header>
<img src="media/pizza-served.jpg" width="600" height="277" alt="Pizza Logo"/>
<h1>Pizza Order Form</h1>
</header>
<form id="myForm" name="myForm" method="post" action="http://lavalamp.dyndns.org/~mult114/pizzaorder_olympic.php" onsubmit="return validateForm();" target="_blank">
<input type="hidden" name="difficulty" value="1" />
<fieldset id="contactinfo">
<legend style="font-size: larger;"><strong>Contact Information</strong></legend>
<label for="firstnameinput">First Name</label>
<input type="text" id="firstnameinput" name="FirstName_tf" /><br>
<label for="lastnameinput">Last Name</label>
<input type="text" id="lastnameinput" name="LastName_tf" /><br>
<label for="addrinput">Address</label>
<input type="text" id="addrinput" name="Address_tf" /><br>
<label for="phoneinput">Phone</label>
<input type="text" id="phoneinput" name="Phone_tf" /><br>
<label for="emailinput">Email Address</label>
<input type="email" id="emailinput" name="Email_tf" />
</fieldset>
<fieldset id="orderinfo">
<legend style="font-size: larger;"><strong>Order</strong></legend>
<fieldset id="pizzasize">
<legend>Pizza Size</legend>
<input type="radio" id="smallsize" name="Size_rg" value="10" onclick="calculateSize(this);">
<label for="smallsize">Small 10"</label><br>
<input type="radio" id="mediumsize" name="Size_rg" value="12" onclick="calculateSize(this);">
<label for="mediumsize">Medium 12"</label><br>
<input type="radio" id="largesize" name="Size_rg" value="15" onclick="calculateSize(this);">
<label for="largesize">Large 15"</label>
</fieldset>
<fieldset id="toppingbox">
<legend>Topping(s)</legend>
<input type="checkbox" id="anchovies" name="Anchovies_cb" value="yes" onclick="toppingOptionPrice(this);">
<label for="anchovies">Anchovies</label><br>
<input type="checkbox" id="doublecheese" name="DoubleCheese_cb" value="yes" onclick="toppingOptionPrice(this);">
<label for="doublecheese">Double Cheese</label><br>
<input type="checkbox" id="pepperoni" name="Pepperoni_cb" value="yes" onclick="toppingOptionPrice(this);">
<label for="pepperoni">Pepperoni</label><br>
<input type="checkbox" id="mushrooms" name="Mushroom_cb" value="yes" onclick="toppingOptionPrice(this);">
<label for="mushrooms">Mushrooms</label><br>
</fieldset>
<fieldset id="instructions">
<legend>Special Instructions</legend>
<textarea id="textarea" name="instructions" rows="5" cols="50" placeholder="Enter your message here!(special requests, delivery details, etc.)"></textarea>
</fieldset>
</fieldset>
<fieldset id="payments">
<legend style="font-size: larger;"><strong>Payment</strong></legend>
<label>Select Payment Method:</label>
<select id="paymethods" name="Payment_menu" required="required">
<option value="select">- Select One -</option>
<option value="cash">Cash</option>
<option value="debit">Debit</option>
<option value="credit">Credit Card</option>
</select>
</fieldset>
<fieldset id="calcprice">
<legend style="font-size: larger;"><strong>Order Total</strong></legend>
<label for="subtotal">SubTotal $:</label>
<input type="text" id="subtotal" name="SubTotal_tb" readonly><br>
<label for="pstToPay">PST $:</label>
<input type="text" id="pstToPay" name="PST_tb" readonly><br>
<label for="gstToPay">GST $:</label>
<input type="text" id="gstToPay" name="GST_tb" readonly><br>
<label for="total">Total $:</label>
<input type="text" id="total" name="Total_tb" readonly><br>
</fieldset>
<input type="submit" name="Submit_but">
</form>
</body>
</html>

your code is correct. you are getting wrong because of the calculation. Try with this equation:-
let pstToPay = subtotal * pst;
pstToPay = parseFloat(pstToPay.toFixed(2));
let gstToPay = subtotal * gst;
gstToPay = parseFloat(gstToPay.toFixed(2));
And if you want to remove zeroes you can solve it by this:
.toFixed(2).replace(/0+$/, "") // this will make 4.50 = 4.5
const priceSmall = 4.00;
const priceMedium = 5.00;
const priceLarge = 7.00;
const priceToppings = 0.50;
const pst = .07;
const gst = .07
let subtotal = 0;
////////////////Pizza size calculation///////////////
function calculateSize(element) {
if (element == null) {
return;
}
switch(element.value) {
case "10":
subtotal = priceSmall;
break;
case "12":
subtotal = priceMedium;
break;
case "15":
subtotal = priceLarge;
break;
}
recalculateTotal();
}
/////////////Topping calculation////////////
function toppingOptionPrice(element) {
if (element.checked) {
subtotal += priceToppings;
} else {
subtotal -= priceToppings;
}
recalculateTotal();
}
////////////Total//////////////
function recalculateTotal() {
let pstToPay = subtotal * pst;
pstToPay = parseFloat(pstToPay.toFixed(2));
let gstToPay = subtotal * gst;
gstToPay = parseFloat(gstToPay.toFixed(2));
let total = subtotal +pstToPay + gstToPay;
document.getElementById("subtotal").value = subtotal.toFixed(2).replace(/0+$/, "") ;
document.getElementById("pstToPay").value = pstToPay.toFixed(2);
document.getElementById("gstToPay").value = gstToPay.toFixed(2);
document.getElementById("total").value = total.toFixed(2);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pizza Order Form</title>
<link rel="stylesheet" href="css/style.css">
<script src="scripts/script.js"></script>
<body>
<header>
<img src="media/pizza-served.jpg" width="600" height="277" alt="Pizza Logo"/>
<h1>Pizza Order Form</h1>
</header>
<form id="myForm" name="myForm" method="post" action="http://lavalamp.dyndns.org/~mult114/pizzaorder_olympic.php" onsubmit="return validateForm();" target="_blank">
<input type="hidden" name="difficulty" value="1" />
<fieldset id="contactinfo">
<legend style="font-size: larger;"><strong>Contact Information</strong></legend>
<label for="firstnameinput">First Name</label>
<input type="text" id="firstnameinput" name="FirstName_tf" /><br>
<label for="lastnameinput">Last Name</label>
<input type="text" id="lastnameinput" name="LastName_tf" /><br>
<label for="addrinput">Address</label>
<input type="text" id="addrinput" name="Address_tf" /><br>
<label for="phoneinput">Phone</label>
<input type="text" id="phoneinput" name="Phone_tf" /><br>
<label for="emailinput">Email Address</label>
<input type="email" id="emailinput" name="Email_tf" />
</fieldset>
<fieldset id="orderinfo">
<legend style="font-size: larger;"><strong>Order</strong></legend>
<fieldset id="pizzasize">
<legend>Pizza Size</legend>
<input type="radio" id="smallsize" name="Size_rg" value="10" onclick="calculateSize(this);">
<label for="smallsize">Small 10"</label><br>
<input type="radio" id="mediumsize" name="Size_rg" value="12" onclick="calculateSize(this);">
<label for="mediumsize">Medium 12"</label><br>
<input type="radio" id="largesize" name="Size_rg" value="15" onclick="calculateSize(this);">
<label for="largesize">Large 15"</label>
</fieldset>
<fieldset id="toppingbox">
<legend>Topping(s)</legend>
<input type="checkbox" id="anchovies" name="Anchovies_cb" value="yes" onclick="toppingOptionPrice(this);">
<label for="anchovies">Anchovies</label><br>
<input type="checkbox" id="doublecheese" name="DoubleCheese_cb" value="yes" onclick="toppingOptionPrice(this);">
<label for="doublecheese">Double Cheese</label><br>
<input type="checkbox" id="pepperoni" name="Pepperoni_cb" value="yes" onclick="toppingOptionPrice(this);">
<label for="pepperoni">Pepperoni</label><br>
<input type="checkbox" id="mushrooms" name="Mushroom_cb" value="yes" onclick="toppingOptionPrice(this);">
<label for="mushrooms">Mushrooms</label><br>
</fieldset>
<fieldset id="instructions">
<legend>Special Instructions</legend>
<textarea id="textarea" name="instructions" rows="5" cols="50" placeholder="Enter your message here!(special requests, delivery details, etc.)"></textarea>
</fieldset>
</fieldset>
<fieldset id="payments">
<legend style="font-size: larger;"><strong>Payment</strong></legend>
<label>Select Payment Method:</label>
<select id="paymethods" name="Payment_menu" required="required">
<option value="select">- Select One -</option>
<option value="cash">Cash</option>
<option value="debit">Debit</option>
<option value="credit">Credit Card</option>
</select>
</fieldset>
<fieldset id="calcprice">
<legend style="font-size: larger;"><strong>Order Total</strong></legend>
<label for="subtotal">SubTotal $:</label>
<input type="text" id="subtotal" name="SubTotal_tb" readonly><br>
<label for="pstToPay">PST $:</label>
<input type="text" id="pstToPay" name="PST_tb" readonly><br>
<label for="gstToPay">GST $:</label>
<input type="text" id="gstToPay" name="GST_tb" readonly><br>
<label for="total">Total $:</label>
<input type="text" id="total" name="Total_tb" readonly><br>
</fieldset>
<input type="submit" name="Submit_but">
</form>
</body>
</html>

You can use math.round() function available in js to round your values.
For example say your total value can be rounded of by providing math.round() func to it.
let total = math.round(subtotal + pstToPay + gstToPay);
Reference page:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round

Related

Trying to set a radio button in HTML document using javascript with data from cookie

I have a question. I got this registration form that stores the values into a cookie based on an ID name. When you go back to the same registration form and fill in the ID name that was already saved in a cookie, it will pull the data from cookie and prefill the form.
I have the following code and it works on form fields, but not on radio buttons. Not sure what is going on with radio buttons
//This function fills in the form based on entered conference ID
function fillForm(name) {
var cookie = getCookie(name).toString();
var newCookie = decodeURIComponent(cookie);
var newArray = newCookie.split(";");
//For testing values to make sure they're there
alert(newArray);
document.getElementById("title").value = newArray[0];
document.getElementById("firstname").value = newArray[1];
document.getElementById("lastname").value = newArray[2];
document.getElementById("addressone").value = newArray[3];
document.getElementById("addresstwo").value = newArray[4];
document.getElementById("city").value = newArray[5];
document.getElementById("state").value = newArray[6];
document.getElementById("zipcode").value = newArray[7];
document.getElementById("tel").value = newArray[8];
document.getElementById("email").value = newArray[9];
document.getElementById("website").value = newArray[10];
document.getElementById("position").value = newArray[11];
document.getElementById("companyname").value = newArray[12];
if(newArray[13]) {
document.getElementById("mealone").checked = true;
}
else {
document.getElementById("mealtwo").checked = true;
}
if(newArray[15]) {
document.getElementById("sesonea").checked = true;
}
else if(newArray[16]) {
document.getElementById("sesoneb").checked = true;
}
else {
document.getElementById("sesonec").checked = true;
}
if(newArray[18]) {
document.getElementById("sestwoa").checked = true;
}
else if(newArray[19]) {
document.getElementById("sestwob").checked = true;
}
else {
document.getElementById("sestwoc").checked = true;
}
if(newArray[21]) {
document.getElementById("sesthreea").checked = true;
}
else if(newArray[22]) {
document.getElementById("sesthreeb").checked = true;
}
else {
document.getElementById("sesthreec").checked = true;
}
document.getElementById("billfirstname").value = newArray[24];
document.getElementById("billlastname").value = newArray[25];
if(newArray[26]) {
document.getElementById("carda").checked = true;
}
else if(newArray[27]) {
document.getElementById("cardb").checked = true;
}
else {
document.getElementById("cardc").checked = true;
}
document.getElementById("cardnumber").value = newArray[29];
document.getElementById("csv").value = newArray[30];
document.getElementById("cardexpmonth").value = newArray[31];
document.getElementById("cardexpyear").value = newArray[32];
}
It's driving me nuts. I setup an alert to make sure I can see all the data correctly in the array, but it's not selecting the correct radio buttons.
Edit: HTML form:
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="js/jsdefault.js"></script>
<link rel="stylesheet" href="css/webdefault.css">
<meta charset="UTF-8">
<meta name="description" content="Conference Website">
<meta name="keywords" content="Conference, website">
<meta name="author" content="Rafal Dudek">
<meta name="robots" content="all">
<title>Conference Registration</title>
</head>
<body>
<div id="header">
<nav>
<ul>
<li>Index</li>
<li>Awards</li>
<li>Activities</li>
<li>Meals</li>
<li>Keynote</li>
<li>Workshop Schedule</li>
<li>Registration</li>
</ul>
</nav>
</div>
<div id="main">
<form action="thankyou.html" id="registration" onsubmit="return check()" method="get">
<fieldset>
<legend>Conference ID</legend>
<label>Conference ID: <input type="text" oninput="fillForm(this.value)" id="confID" name="confID" size="6" maxlength="6" required="required" pattern="[0-9]{6}" placeholder="123456" title="Enter a 6 digit conference ID number"></label><br />
</fieldset>
<fieldset>
<legend>Personal Information</legend>
<label for="title">Title:</label>
<select id="title">
<option value="Mr.">Mr.</option>
<option value="Ms.">Ms.</option>
<option value="Mrs.">Mrs.</option>
</select><br />
<label>First Name: <input type="text" id="firstname" name="firstname" size="30" maxlength="100" required="required" pattern="[a-zA-Z]+" placeholder="First Name" title="Enter your first name"></label><br />
<label>Last Name: <input type="text" id="lastname" name="lastname" size="30" maxlength="100" required="required" pattern="[a-zA-Z\-]+" placeholder="Last Name" title="Enter your last name"></label><br />
<label>Address 1: <input type="text" id="addressone" name="addressone" size="30" maxlength="100" required="required" pattern="[a-zA-Z0-9\ \#]+" placeholder="Address" title="Enter your address"></label><br />
<label>Address 2: <input type="text" id="addresstwo" name="addresstwo" size="30" maxlength="100" pattern="[a-zA-Z0-9\ \#]+" title="Optional: Enter part 2 of your address"></label><br />
<label>City: <input type="text" id="city" name="city" size="30" maxlength="100" required="required" pattern="[a-zA-Z\ ]+" placeholder="City" title="Enter your city"></label><br />
<label title="state">State:</label>
<select title="state" id="state">
<option value="AL">AL</option>
<option value="AK">AK</option>
<option value="AR">AR</option>
<option value="AZ">AZ</option>
<option value="CA">CA</option>
<option value="CO">CO</option>
<option value="CT">CT</option>
<option value="DC">DC</option>
<option value="DE">DE</option>
<option value="FL">FL</option>
<option value="GA">GA</option>
<option value="HI">HI</option>
<option value="IA">IA</option>
<option value="ID">ID</option>
<option value="IL">IL</option>
<option value="IN">IN</option>
<option value="KS">KS</option>
<option value="KY">KY</option>
<option value="LA">LA</option>
<option value="MA">MA</option>
<option value="MD">MD</option>
<option value="ME">ME</option>
<option value="MI">MI</option>
<option value="MN">MN</option>
<option value="MO">MO</option>
<option value="MS">MS</option>
<option value="MT">MT</option>
<option value="NC">NC</option>
<option value="NE">NE</option>
<option value="NH">NH</option>
<option value="NJ">NJ</option>
<option value="NM">NM</option>
<option value="NV">NV</option>
<option value="NY">NY</option>
<option value="ND">ND</option>
<option value="OH">OH</option>
<option value="OK">OK</option>
<option value="OR">OR</option>
<option value="PA">PA</option>
<option value="RI">RI</option>
<option value="SC">SC</option>
<option value="SD">SD</option>
<option value="TN">TN</option>
<option value="TX">TX</option>
<option value="UT">UT</option>
<option value="VT">VT</option>
<option value="VA">VA</option>
<option value="WA">WA</option>
<option value="WI">WI</option>
<option value="WV">WV</option>
<option value="WY">WY</option>
</select><br />
<label>Zip Code: <input type="text" id="zipcode" name="zipcode" size="10" maxlength="10" required="required" pattern="[0-9]{5}\-[0-9]{4}" placeholder="Zip Code" title="Enter zip code"></label><br />
<label>Telephone: <input type="text" id="tel" name="tel" size="30" maxlength="100" required="required" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" placeholder="Telephone" title="Enter telephone number"></label><br />
<label>Email: <input type="email" id="email" name="email" size="30" maxlength="100" required="required" pattern="([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Zaz]{2,4})" placeholder="example#example.com" title="Enter email address"></label><br />
</fieldset>
<fieldset>
<legend>Company Information</legend>
<label>Company Website: <input type="url" id="website" name="website" size="30" maxlength="100" placeholder="www.example.com" title="Enter website URL"></label><br />
<label>Position: <input type="text" id="position" name="position" size="30" maxlength="100" required="required" pattern="[a-zA-Z0-9\ \#]+" placeholder="Position" title="Enter your position"></label><br />
<label>Company Name: <input type="text" id="companyname" name="companyname" size="30" maxlength="100" required="required" pattern="[a-zA-Z0-9\ \#]+" placeholder="Company Name" title="Enter company name"></label><br />
</fieldset>
<fieldset>
<legend>Dining Information</legend>
<p>
Would you like a full meal or just day 2 dinner?<br />
<label><input type="radio" id="mealone" name="meal" value="full" required/> Full Meal ($250)</label>
<label><input type="radio" id="mealtwo" name="meal" value="part"/> Day 2 dinner only ($75)</label>
</p>
</fieldset>
<fieldset>
<legend>Workshop Information</legend>
<p>
Which workshops would you like to join?<br />
Outdoors Theme:
<label><input type="radio" id="sesonea" name="session_1" value="workshop_1" required /> Lawn Maintenance</label>
<label><input type="radio" id="sesoneb" name="session_1" value="workshop_2"/> Landscaping Ideas</label>
<label><input type="radio" id="sesonec" name="session_1" value="workshop_3" /> Pest Control</label><br />
Home Improvement Theme:
<label><input type="radio" id="sestwoa" name="session_2" value="workshop_4" /> Kitchen Remodeling</label>
<label><input type="radio" id="sestwob" name="session_2" value="workshop_5"/> Bathroom Remodeling</label>
<label><input type="radio" id="sestwoc" name="session_2" value="workshop_6" /> Home Improvement Ideas</label><br />
Repair Basics Theme:
<label><input type="radio" id="sesthreea" name="session_3" value="workshop_7" required/> General Appliance Troubleshooting</label>
<label><input type="radio" id="sesthreeb" name="session_3" value="workshop_8"/> Heat and A/C Unit Maintenance</label>
<label><input type="radio" id="sesthreec" name="session_3" value="workshop_9" /> Plumbing Basics</label><br />
</p>
</fieldset>
<fieldset>
<legend>Billing Information:</legend>
<label>Billing First Name: <input type="text" id="billfirstname" name="billfirstname" size="30" maxlength="100" required="required" pattern="[a-zA-Z]+" placeholder="First Name" title="Enter first name"></label><br />
<label>Billing Last Name: <input type="text" id="billlastname" name="billlastname" size="30" maxlength="100" required="required" pattern="[a-zA-Z\-]+" placeholder="Last Name" title="Enter last name"></label><br />
<p>
Card Type:<br />
<label><input type="radio" id="carda" name="card" value="visa" /> Visa</label>
<label><input type="radio" id="cardb" name="card" value="mastercard" required/> MasterCard</label>
<label><input type="radio" id="cardc" name="card" value="americanexpress"/> American Express</label>
</p>
<label>Card Number: <input type="text" id="cardnumber" name="cardnumber" size="16" maxlength="16" required="required" pattern="[0-9]{16}" placeholder="0000000000000000" title="Enter credit card number"></label><br />
<label>Card Security Value: <input type="text" id="csv" name="csv" size=4 maxlength="4" required="required" pattern="[0-9]{4}" placeholder="000" title="Enter CSV number"></label><br />
<label>Exp. Month (two digits): <input type="text" id="cardexpmonth" name="cardexpmonth" size="2" maxlength="2" required="required" pattern="(0[1-9]|1[0-2])" placeholder="MM" title="Enter two digit month"></label><br />
<label>Exp. Year (four digits): <input type="text" id="cardexpyear" name="cardexpyear" size="4" maxlength="4" required="required" pattern="[2][0]([1-2][6-9])" placeholder="YYYY" title="Enter four digit year"></label><br />
<input type="submit" value="Submit" />
</fieldset>
</form>
</div>
<div id="footer">
<address>
<small>
Contact Information:<br>
Peter John<br>
12345 Grape St.<br>
Thornton, CO 80233<br>
Telephone: 303-555-6666<br>
E-mail: peter.john#gmail.com
</small>
</address>
</div>
</body>
</html>
Adding get and set cookie functions too just in case:
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
//This function gets cookie value based on conference ID
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
Cookies are stored as Strings so when you do if(newArray[1]) you are saying if("false") or if("true") which in javascript
The result is false if the argument is the empty String (its length is zero); otherwise the result is true
source: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
and answer that gave source: https://stackoverflow.com/a/8693015/1309377
Any of your "false" are treated as true
to fix this you should be doing newArray[1] == "true"
//This function fills in the form based on entered conference ID
var newArray = ["true", "false", "true"] //newCookie.split(";");
if (newArray[0] == "true") {
document.getElementById("mealone").checked = true;
} else {
document.getElementById("mealtwo").checked = true;
}
if (newArray[1] == "true") {
document.getElementById("sesonea").checked = true;
} else if (newArray[2] == "true") {
document.getElementById("sesoneb").checked = true;
} else {
document.getElementById("sesonec").checked = true;
}
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="js/jsdefault.js"></script>
<link rel="stylesheet" href="css/webdefault.css">
<meta charset="UTF-8">
<meta name="description" content="Conference Website">
<meta name="keywords" content="Conference, website">
<meta name="author" content="Rafal Dudek">
<meta name="robots" content="all">
<title>Conference Registration</title>
</head>
<body>
<div id="main">
<form action="thankyou.html" id="registration" onsubmit="return check()" method="get">
<fieldset>
<legend>Dining Information</legend>
<p>
Would you like a full meal or just day 2 dinner?<br />
<label><input type="radio" id="mealone" name="meal" value="full" required/> Full Meal ($250)</label>
<label><input type="radio" id="mealtwo" name="meal" value="part"/> Day 2 dinner only ($75)</label>
</p>
</fieldset>
<fieldset>
<legend>Workshop Information</legend>
<p>
Which workshops would you like to join?<br /> Outdoors Theme:
<label><input type="radio" id="sesonea" name="session_1" value="workshop_1" required /> Lawn Maintenance</label>
<label><input type="radio" id="sesoneb" name="session_1" value="workshop_2"/> Landscaping Ideas</label>
<label><input type="radio" id="sesonec" name="session_1" value="workshop_3" /> Pest Control</label>
</p>
</fieldset>
</body>
</html>

validation on states with postcode and checkbox list text area

So far my java script only consist of the age validation but I need to have more which is when the user selects a state the first digit of the postcode should be as such VIC = 3 OR 8, NSW = 1 OR 2 ,QLD = 4 OR 9 ,NT = 0 ,WA = 6 ,SA=5 ,TAS=7 ,ACT= 0. Another one is when a user selects "Other skill" in the checkbox list they have to write in it so it cannot be blank. How do I go about doing these validations without using any library code?
"use strict";
/*get variables from form and check rules*/
function validate() {
var errMsg = ""; /* stores the error message */
var result = true; /* assumes no errors */
var age = document.getElementById("age").value;
var state = document.getElementById("state").value;
var postcode = document.getElementById("postcode").value;
//get varibles from form and check rules here
// if something is wrong set result = false, and concatenate error message
var today = new Date();
var age = today.getFullYear() - date.getFullYear();
if (age <= 15 && age >= 80) { // Outside age ranges.
errMsg = errMsg + "You must be between the ages of 15 to 80 to apply for this job\n"
result = false;
}
/** if (/^[3][0-9]{3}$/) for postcode*/
if (errMsg != "") { //only display message box if there is something to show
alert(errMsg);
}
return result; //if false the information will not be sent to the server
}
function init() {
var regForm = document.getElementById("regForm"); // get ref to the HTML element
regForm.onsubmit = validate; //register the event listener
}
window.onload = init;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="description" content="Prototype Website" />
<meta name="keywords" content="HTML, CSS, JavaScript" />
<title>The Virtual World</title>
<link href="styles/style.css" rel="stylesheet" />
<script src="apply.js"></script>
</head>
<body>
<article>
<header>
<h1>The Virtual World</h1>
<nav>
<p class="menu">Home</p>
<p class="menu">Jobs</p>
<p class="menu">Apply</p>
<p class="menu">About</p>
<p class="menu">Enhancements</p>
</nav>
</header>
<section id="required">
<h5>All fields with * are required</h5>
</section>
<form id="regForm" method="post" action="http://mercury.swin.edu.au/it000000/formtest.php">
<fieldset>
<legend>Job Application</legend>
<p><label for="JobID">*Job ID:</label>
<input type="text" name="JobID" id="JobID" maxlength="5" size="10" pattern="^[a-zA-Z]{2}[0-9]{3}$" required="required" /></p>
<section id="choose">
<h5>Please choose from QM593 or CS197</h5>
</section>
<fieldset>
<legend>Personal Details</legend>
<p><label for="title">*Title:</label>
<select name="title" id="title" required="required">
<option value="">Please Select</option>
<option value="title">Dr</option>
<option value="title">Mr</option>
<option value="title">Miss</option>
<option value="title">Mrs</option>
<option value="title">Ms</option>
</select></p>
<p><label for="firstName">*First Name:</label>
<input type="text" name="firstName" id="firstName" maxlength="20" size="20" pattern="^[a-zA-Z ]+$" required="required" />
<label for="familyName">*Family Name:</label>
<input type="text" name="familyName" id="familyName" maxlength="20" size="20" pattern="^[a-zA-Z ]+$" required="required" /></p>
<p><label for="midName">Middle Name:</label>
<input type="text" name="midName" id="midName" maxlength="20" size="20" pattern="^[a-zA-Z ]+$" /></p>
<p><label for="dob">*Date of Birth:</label>
<input type="text" name="dob" id="dob" placeholder="dd/mm/yyyy" pattern="\d{1,2}/\d{1,2}/\d{4}" maxlength="10" size="10" required="required" /></p>
<p>*Gender:
<label for="male">Male</label>
<input type="radio" id="male" name="sex" value="male" required="required" />
<label for="female">Female</label>
<input type="radio" id="female" name="sex" value="female" required="required" /></p>
<p><label for="street">*Street Address:</label>
<input type="text" name="street" id="street" maxlength="40" size="30" required="required" /></p>
<p><label for="suburb">*Suburb/town:</label>
<input type="text" name="suburb" id="suburb" maxlength="40" size="20" required="required" /></p>
<p><label for="state">*State:</label>
<select name="state" id="state" required="required">
<option value="">Please Select</option>
<option value="state">VIC</option>
<option value="state">NSW</option>
<option value="state">QLD</option>
<option value="state">NT</option>
<option value="state">WA</option>
<option value="state">SA</option>
<option value="state">TAS</option>
<option value="state">ACT</option>
</select></p>
<p><label for="postcode">*Postcode:</label>
<input type="text" name="postcode" id="postcode" minlength="4" maxlength="4" size="10" pattern="^[0-9]{4}$" required="required" /></p>
<p><label for="email">*Email:</label>
<input type="email" name="email" id="email" size="30" required="required" /></p>
<p><label for="number">*Phone number:</label>
<input type="tel" name="number" id="number" minlength="8" maxlength="12" size="10" required="required" /></p>
<p>Skill list:</p>
<p><label for="C/C+">C/C+</label>
<input type="checkbox" id="C/C+" name="category[]" checked="checked" /></p>
<p><label for="XML">XML</label>
<input type="checkbox" id="XML" name="category[]" /></p>
<p><label for="Java">Java</label>
<input type="checkbox" id="Java" name="category[]" /></p>
<p><label for="Python">Python</label>
<input type="checkbox" id="Python" name="category[]" /></p>
<p><label for="SQL">SQL</label>
<input type="checkbox" id="SQL" name="category[]" /></p>
<p><label for="PERL">PERL</label>
<input type="checkbox" id="PERL" name="category[]" /></p>
<p><label for="MySQL">MySQL</label>
<input type="checkbox" id="MySQL" name="category[]" /></p>
<p><label for="Windows">Windows</label>
<input type="checkbox" id="Windows" name="category[]" /></p>
<p><label for="UNIX">UNIX</label>
<input type="checkbox" id="UNIX" name="category[]" /></p>
<p><label for="Linux">Linux</label>
<input type="checkbox" id="Linux" name="category[]" /></p>
<p><label for="other">Other Skills:</label> </p>
<p>
<textarea id="other" name="other" rows="8" cols="70" placeholder="Please write any other skills you may have here..."></textarea>
</p>
</fieldset>
</fieldset>
<input type="submit" value="Apply" />
<input type="reset" value="Reset Application" />
</form>
</article>
</body>
</html>
Try something using match jquery like below.
"use strict";
/*get variables from form and check rules*/
function validate() {
var errMsg = "";
/* stores the error message */
if($('#state').find(':selected').text() === 'VIC' && $('#postcode').val().match('^3')){
//do your codings
}
else{
alert(errMsg);
}
}
function init() {
var regForm = document.getElementById("regForm"); // get ref to the HTML element
regForm.onsubmit = validate; //register the event listener
}
window.onload = init;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<body>
<article>
<header>
<h1>The Virtual World</h1>
</header>
<section id="required">
<h5>All fields with * are required</h5>
</section>
<form id="regForm" method="post" action="http://mercury.swin.edu.au/it000000/formtest.php">
<fieldset>
<legend>Personal Details</legend>
<p><label for="state">*State:</label>
<select name="state" id="state" required="required">
<option value="">Please Select</option>
<option value="state">VIC</option>
<option value="state">NSW</option>
<option value="state">QLD</option>
<option value="state">NT</option>
<option value="state">WA</option>
<option value="state">SA</option>
<option value="state">TAS</option>
<option value="state">ACT</option>
</select></p>
<p><label for="postcode">*Postcode:</label>
<input type="text" name="postcode" id="postcode" minlength="4" maxlength="4" size="10" pattern="^[0-9]{4}$" required /></p>
</fieldset>
<input type="submit" value="Apply" />
<input type="reset" value="Reset Application" />
</form>
</article>
</body>
</html>
Use regex to validate post code.
Try these two functions to validate postcode and skills
HTML - add new checkbox to Other. I've only added testing fields to the form.
function validate() {
if(!validateOtherSkills() || validatePostCode()){
result = false;
}
return result; //if false the information will not be sent to the server
}
function validateOtherSkills(){
var state = document.getElementById("OtherSK").checked;
if(state && document.getElementById("other").value.trim().length===0){
alert('Specify other skills');
return false;
}
return true;
}
function validatePostCode(){
var postcode = document.getElementById("postcode").value;
var state = document.getElementById("state").options[document.getElementById("state").selectedIndex].text;
var regex;
//VIC = 3 OR 8, NSW = 1 OR 2 ,QLD = 4 OR 9 ,NT = 0 ,WA = 6 ,SA=5 ,TAS=7 ,ACT= 0.
switch (state) {
case "Please Select":
return false;
case "VIC":
regex = new RegExp(/(3|8)\d+/);
break;
case "NSW":
regex = new RegExp(/(1|2)\d+/);
break;
case "QLD":
regex = new RegExp(/(4|9)\d+/);
break;
case "NT":
regex = new RegExp(/0\d+/);
break;
case "WA":
regex = new RegExp(/6\d+/);
break;
case "SA":
regex = new RegExp(/5\d+/);
break;
case "TAS":
regex = new RegExp(/7\d+/);
break;
case "ACT":
regex = new RegExp(/0\d+/);
break;
}
var result = postcode.match(regex);
if(!result){
alert('Postal code invalid');
}
return result;
}
function init() {
var regForm = document.getElementById("regForm"); // get ref to the HTML element
regForm.onsubmit = validate; //register the event listener
}
window.onload = init;
<article>
<section id="required">
<h5>All fields with * are required</h5>
</section>
<form id="regForm" method="post" action="">
<fieldset>
<legend>Job Application</legend>
<section id="choose">
<h5>Please choose from QM593 or CS197</h5>
</section>
<fieldset>
<legend>Personal Details</legend>
<p><label for="state">*State:</label>
<select name="state" id="state" required="required">
<option value="">Please Select</option>
<option value="state">VIC</option>
<option value="state">NSW</option>
<option value="state">QLD</option>
<option value="state">NT</option>
<option value="state">WA</option>
<option value="state">SA</option>
<option value="state">TAS</option>
<option value="state">ACT</option>
</select></p>
<p><label for="postcode">*Postcode:</label>
<input type="text" name="postcode" id="postcode" minlength="4" maxlength="4" size="10" pattern="^[0-9]{4}$" required="required" /></p>
<p>Skill list:</p>
<p><label for="C/C+">C/C+</label>
<input type="checkbox" id="C/C+" name="category[]" checked="checked" /></p>
<p><label for="XML">XML</label>
<input type="checkbox" id="XML" name="category[]" /></p>
<p><label for="Java">Java</label>
<input type="checkbox" id="Java" name="category[]" /></p>
<p><label for="Python">Python</label>
<input type="checkbox" id="Python" name="category[]" /></p>
<p><label for="SQL">SQL</label>
<input type="checkbox" id="SQL" name="category[]" /></p>
<p><label for="PERL">PERL</label>
<input type="checkbox" id="PERL" name="category[]" /></p>
<p><label for="MySQL">MySQL</label>
<input type="checkbox" id="MySQL" name="category[]" /></p>
<p><label for="Windows">Windows</label>
<input type="checkbox" id="Windows" name="category[]" /></p>
<p><label for="UNIX">UNIX</label>
<input type="checkbox" id="UNIX" name="category[]" /></p>
<p><label for="Linux">Linux</label>
<input type="checkbox" id="Linux" name="category[]" /></p>
<p><label for="OtherSK">Other</label>
<input type="checkbox" id="OtherSK" name="category[]" /></p>
<p><label for="other">Other Skills:</label> </p>
<p>
<textarea id="other" name="other" rows="8" cols="70" placeholder="Please write any other skills you may have here..."></textarea>
</p>
</fieldset>
</fieldset>
<input type="submit" value="Apply" />
<input type="reset" value="Reset Application" />
</form>
</article>

Printing values of all radio buttons to a textarea?

So I have a list of radio buttons all in one span that when encode is pressed I want to use JavaScript to print the values of these radio buttons to a text area (id of: BINARYBit), using the function bin2dec. I need these values to be 1 if the radio is selected and 0 if it is not. I have added a snippet below that shows my whole document.
Any thoughts ?
thanks!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="bootstrap.css" />
</head>
<body>
<div class="container">
<div class="col-lg-8">
<label for="HEXBit">Input the Bitmask Here</label>
<br/>
<input type="text" class="form-control" id="DECBit" />
<br/>
<input type="submit" class="btn btn-primary btn-sm" id="Submit" value="Decode" onclick="dec2bin();" />
<br/>
<input type="text" class="form-control" id="BINARYBit" disabled="disabled" />
<br/>
<input type="submit" class="btn btn-primary btn-sm" id="SubmitCon" value="Encode" onclick="bin2dec();" />
<br/>
<span id="radiocheck">
<br/>
<input type="radio" id="BinaryMessage" />
<label for="BinaryMessage">Send Binary Message</label>
<br/>
<input type="radio" id="Param1" />
<label for="Param1">Param1</label>
<br/>
<input type="radio" id="MDMID" />
<label for="MDMID">Modem ID </label>
<br/>
<input type="radio" id="GPIO" />
<label for="GPIO">GPIO</label>
<br/>
<input type="radio" id="AnalogDigi1" />
<label for="AnalogDigi1">Digital/Analog 1</label>
<br/>
<input type="radio" id="AnalogDigi2" />
<label for="AnalogDigi2">Digital/Analog 2</label>
<br/>
<input type="radio" id="StoreMsg" />
<label for="StoreMsg">Save Message if no GPRS</label>
<br/>
<input type="radio" id="InputNum" />
<label for="InputNum">Input Event Number</label>
<br/>
<input type="radio" id="GPSDate" />
<label for="GPSDate">GPS Date</label>
<br/>
<input type="radio" id="GPSStatus" />
<label for="GPSStatus">GPS Status</label>
<br/>
<input type="radio" id="GPSLat" />
<label for="GPSLat">Latitude</label>
<br/>
<input type="radio" id="GPSLong" />
<label for="GPSLong">Longitude</label>
<br/>
<input type="radio" id="GPSSpeed" />
<label for="GPSSpeed">GPS Speed (Knots)</label>
<br/>
<input type="radio" id="GPSHeading" />
<label for="GPSHeading">Heading</label>
<br/>
<input type="radio" id="GPSTime" />
<label for="GPSTime">GPS Time</label>
<br/>
<input type="radio" id="GPSAlt" />
<label for="GPSAlt">Altitude</label>
<br/>
<input type="radio" id="GPSNoSAT" />
<label for="GPSNoSAT">Number of GPS Satelites</label>
<br/>
<input type="radio" id="LowPowerMsg" />
<label for="LowPowerMsg">Stop Messages In Low Power</label>
<br/>
<input type="radio" id="SMSNoGPRS" />
<label for="SMSNoGPRS">Send SMS When No GPRS</label>
<br/>
<input type="radio" id="LastKnownGPS" />
<label for="LastKnownGPS">Use Last Known GPS When Unavaliable</label>
<br/>
<input type="radio" id="GPSOdo" />
<label for="GPSOdo">Odometer</label>
<br/>
<input type="radio" id="RTCTime" />
<label for="RTCTime">RTC Time</label>
<br/>
<input type="radio" id="ShortID" />
<label for="ShortID">Use Short Modem ID</label>
<br/>
<input type="radio" id="BattLVL" />
<label for="BattLVL">Power Level</label>
<br/>
<input type="radio" id="GPSOverSpeed" />
<label for="GPSOverSpeed">GPS Overspeed Data</label>
<br/>
<input type="radio" value="1" id="PCELL" />
<label for="PCELL">PCELL Data</label>
<br/>
<input type="radio" id="GPSALTOvr" />
<label for="GPSALTOvr">GPS Alternative Over Speed</label>
</span>
</div>
</div>
</body>
<script language="JavaScript">
function dec2bin() {
var dec = document.getElementById("DECBit").value
var val = (dec >>> 0).toString(2);
var pad = "00000000000000000000000000000000";
var answer = pad.substring(0, pad.length - val.length) + val;
var arr = [];
for (var i = 0; i < answer.length; i++) {
arr[i] = (answer.charAt(i) == "1" ? true : false);
}
arr.reverse();
console.log(answer);
console.log(arr);
document.getElementById("BINARYBit").value = answer;
var span = document.getElementById("radiocheck");
var inputs = span.getElementsByTagName("input");
for (var i = 0; i < arr.length; ++i) {
var thing = inputs[i];
thing.checked = arr[i];
}
function bin2dec() {
}
}
</script>
</html>
With native javascript, the best way would be to give all the inputs that you want to check a class like class="item" and then you search for all of these items in the function as so:
function bin2dec() {
var printableEncoded = "",
items = document.getElementsByClassName("item");
// For each item if it's checked include a '1', else a '0'
for (var i = 0; i < items.length; i++) {
printableEncoded += items[i].checked ? "1" : "0";
}
// Change the value of the disabled input to the encoded string
document.getElementById("BINARYBit").value = printableEncoded;
}
Example of HTML:
<input type="radio" value="1" id="PCELL" class="item" />
<label for="PCELL">PCELL Data</label>
solution using jquery
function encode()
{
var value="";
//select all radio buttons
$(".container input[type='radio']").filter(function(i,el){
//check if radio button is checked
value=value + ( ($(el).prop("checked")==true)? "1":"0");
});
$("#BINARYBit").val(value);
}
refereces:
http://api.jquery.com/filter/

getElementsByName looping through all fields returning values using onChange event

I have a contact form. The contact form has inputs, selectors and radio buttons.
Question 1: Using the getElementsByName how do I get the index of a field using the onChange event? Would I use a For Loop?
Question 2: How do I do this with inputs that selectors and radio buttons?
Question 3: Once I get the data from an Index how do I use the index to the ID of the field as I then want to evaluate the data.
Thanks in advance!
Javascript
`// Var for element
var contactname = document.getElementsByName('cf')[1];
//Get value when clicking out of field
contactname.addEventListener('onchange',function(){
console.log(contactname.value);
});`
HTML Form
<!DOCTYPE html>
<html>
<head>
<title>Contact Me</title>
<link rel="stylesheet" type="text/css" href="contactform_Lab8.css">
</head>
<body>
<form id="contactus">
<fieldset>
<label for="name">Name:</label>
<input id="name" type="text" name="cf" autofocus required>
<label for="email">Email:</label>
<input id="email" type="email" name="cf" required>
<label for="phone">Phone:</label>
<input id="phone" type="tel" name="cf" required>
<label for="status">Status:
<select id="status" name="cf" required>
<option value="client">Client</option>
<option value="partner">Partner</option>
<option value="vendor">Vendor</option>
</select>
</label>
<label for="subscribe">
<input id="subscribe" type="checkbox" name="cf" value="check" checked>
Send me your newsletter</label>
<label for="sales">
<label for="support">
<input id="slsSupport" type="radio" name="cf" value="sales" checked>Sales
<input id="slsSupport" type="radio" name="cf" value="support">Support
</label>
</label>
<label for="msg">Message:</label>
<textarea id="msg" name="cf" rows="10" cols="30" required></textarea>
</fieldset>
<fieldset>
<button type="submit">Send</button>
<button type="reset">Reset</button>
</fieldset>
</form>
<script src="contactform_Lab8.js"></script>
</body>
</html>
Try
// Var for element
var contactname = document.getElementsByName("cf");
//Get value when clicking out of field
Array.prototype.slice.call(contactname).forEach(function(elem, index) {
elem.addEventListener("change",function(event) {
// `log` `elem` `index` , `id` , `value`
console.log(index, event.target.id, event.target.value);
}, false);
});
<form id="contactus">
<fieldset>
<label for="name">Name:</label>
<input id="name" type="text" name="cf" autofocus required>
<label for="email">Email:</label>
<input id="email" type="email" name="cf" required>
<label for="phone">Phone:</label>
<input id="phone" type="tel" name="cf" required>
<label for="status">Status:
<select id="status" name="cf" required>
<option value="client">Client</option>
<option value="partner">Partner</option>
<option value="vendor">Vendor</option>
</select>
</label>
<label for="subscribe">
<input id="subscribe" type="checkbox" name="cf" value="check" checked>
Send me your newsletter</label>
<label for="sales">
<label for="support">
<input id="slsSupport" type="radio" name="cf" value="sales" checked>Sales
<input id="slsSupport" type="radio" name="cf" value="support">Support
</label>
</label>
<label for="msg">Message:</label>
<textarea id="msg" name="cf" rows="10" cols="30" required></textarea>
</fieldset>
<fieldset>
<button type="submit">Send</button>
<button type="reset">Reset</button>
</fieldset>
</form>

Javascript calculation not working.

I have one page and two separate script to calculate value but if I repeat two time Javascript in one page it is not working how can I do this?
Please help in this issue. Thanks in advance.
<script type="text/javascript"><!--
function updatesum() {
var total = (document.form.daysone.value -0)*(document.form.daystwo.value -0)* (document.form.amount.value -0)/ (document.form.year.value -0)/ (document.form.month.value -0);
document.form.total.value = total.toFixed(3);
}
//--></script>
<form name="form" action="enter.php" method="post" id="searchform">
<p>
<label class="field">15 Days</label>
<input name="daysone" type="text" value="15" onChange="updatesum()" />
</p>
<p>
<label class="field">686 Days</label>
<input name="daystwo" type="text" value="686" onChange="updatesum()" />
</p>
<p>
<label class="field">Amount </label>
<input name="amount" type="text" value="" onChange="updatesum()" />
</p>
<p>
<label class="field">year </label>
<input name="year" type="text" value="365" onChange="updatesum()" />
</p>
<p>
<label class="field">month </label>
<input name="month" type="text" value="30" onChange="updatesum()" />
</p>
<p>
<label class="field" >Total </label>
<input name="total" type="text" value="" />
</p>
<strong>next one</strong>
<script type="text/javascript"><!--
function updatesum() {
var total1 = (document.form1.days1.value -0)*(document.form1.days1.value -0)* (document.form1.amount1.value -0)/ ;
document.form1.total1.value = total1.toFixed(3);
}
//--></script>
<form name="form1" action="enter.php" method="post" id="searchform">
<p>
<label class="field">15 Days</label>
<input name="days1" type="text" value="15" onChange="updatesum()" />
</p>
<p>
<label class="field">686 Days</label>
<input name="days2" type="text" value="686" onChange="updatesum()" />
</p>
<p>
<label class="field">Amount </label>
<input name="amount1" type="text" value="" onChange="updatesum()" />
</p>
<p>
<label class="field" >Total </label>
<input name="total1" type="text" value="" />
</p>
I think the same name is creating a problem here, Is it necessary to have the same name for both the functions?
Please try to change the name from UpdateSum in second one to something else.
Try to use this function, and replace your with this one.
<script type="text/javascript">
function updatesum() {
var total = (document.form.daysone.value -0)*(document.form.daystwo.value -0)* (document.form.amount.value -0)/ (document.form.year.value -0)/ (document.form.month.value -0);
document.form.total.value = total.toFixed(3);
}
</script>
<form name="form" action="enter.php" method="post" id="searchform">
<p>
<label class="field">15 Days</label>
<input name="daysone" type="text" value="15" onChange="updatesum()" />
</p>
<p>
<label class="field">686 Days</label>
<input name="daystwo" type="text" value="686" onChange="updatesum()" />
</p>
<p>
<label class="field">Amount </label>
<input name="amount" type="text" value="" onChange="updatesum()" />
</p>
<p>
<label class="field">year </label>
<input name="year" type="text" value="365" onChange="updatesum()" />
</p>
<p>
<label class="field">month </label>
<input name="month" type="text" value="30" onChange="updatesum()" />
</p>
<p>
<label class="field" >Total </label>
<input name="total" type="text" value="" />
</p>
The issue is with the duplicate function name.
Since, both the functions have a different calculation, it is better you name them differently and update your html accordingly.
There is another way in which you can do this, but you'll have to pass a parameter to the function which will differentiate between the two forms.
function updatesum(formName) {
var total, total1;
if (formName == 'form') {
total = (document.form.daysone.value - 0) * (document.form.daystwo.value - 0) * (document.form.amount.value - 0) / (document.form.year.value - 0) / (document.form.month.value - 0);
document.form.total.value = total.toFixed(3);
} else if (formName == 'form1') {
total1 = (document.form1.days1.value - 0) * (document.form1.days1.value - 0) * (document.form1.amount1.value - 0);
document.form1.total1.value = total1.toFixed(3);
}
}

Categories