Getting wrong calculation in javascript - javascript

I am having table below.. but Getting wrong calculation in javascript..
<script>
function getPrice(tRate, tMaking, tHandeling, tPrice, tVat, tQuantity, tTotal) {
var obj_tRate = document.getElementById(tRate)
var obj_tMaking = document.getElementById(tMaking)
var obj_tHandeling = document.getElementById(tHandeling)
var obj_tPrice = document.getElementById(tPrice)
var obj_tVat = document.getElementById(tVat)
var obj_tTotal = document.getElementById(tTotal)
var obj_tQuantity = document.getElementById(tQuantity)
if (obj_tRate.value != "" && obj_tMaking.value != "" && obj_tHandeling.value != "") {
obj_tPrice.value = parseFloat(obj_tRate.value) + parseFloat(obj_tMaking.value) + parseFloat(obj_tHandeling.value);
console.log(obj_tPrice.value)
obj_tVat.value = parseFloat(obj_tPrice.value * (1 / 100));
console.log(obj_tVat.value)
obj_tTotal.value = parseFloat(obj_tVat.value + (obj_tPrice.value * obj_tQuantity.value));
console.log(obj_tTotal.value)
}
else {
obj_tPrice.value = "";
}
}
</script>
</head>
<body>
<table>
<tr>
<td>
<input name="grdView$ctl08$txtWaight_F" type="text" id="grdView_ctl08_txtWaight_F" class="classWaight" style="width:60px;" />
</td><td>
<input name="grdView$ctl08$txtQuantity_F" type="text" maxlength="20" id="grdView_ctl08_txtQuantity_F" class="classQuantity" onchange="javascript:return getPrice('grdView_ctl08_txtRate_F','grdView_ctl08_txtMaking_F','grdView_ctl08_txtHandeling_F','grdView_ctl08_txtPrice_F','grdView_ctl08_txtvat_F','grdView_ctl08_txtQuantity_F','grdView_ctl08_txtTotal_F');" style="width:60px;" />
</td><td>
<input name="grdView$ctl08$txtRate_F" type="text" maxlength="8" id="grdView_ctl08_txtRate_F" class="classRate" onchange="javascript:return getPrice('grdView_ctl08_txtRate_F','grdView_ctl08_txtMaking_F','grdView_ctl08_txtHandeling_F','grdView_ctl08_txtPrice_F','grdView_ctl08_txtvat_F','grdView_ctl08_txtQuantity_F','grdView_ctl08_txtTotal_F');" style="width:60px;" />
</td><td>
<input name="grdView$ctl08$txtMaking_F" type="text" id="grdView_ctl08_txtMaking_F" class="classMaking" onchange="javascript:return getPrice('grdView_ctl08_txtRate_F','grdView_ctl08_txtMaking_F','grdView_ctl08_txtHandeling_F','grdView_ctl08_txtPrice_F','grdView_ctl08_txtvat_F','grdView_ctl08_txtQuantity_F','grdView_ctl08_txtTotal_F');" style="width:60px;" />
</td><td>
<input name="grdView$ctl08$txtHandeling_F" type="text" id="grdView_ctl08_txtHandeling_F" class="classHandling" onchange="javascript:return getPrice('grdView_ctl08_txtRate_F','grdView_ctl08_txtMaking_F','grdView_ctl08_txtHandeling_F','grdView_ctl08_txtPrice_F','grdView_ctl08_txtvat_F','grdView_ctl08_txtQuantity_F','grdView_ctl08_txtTotal_F');" style="width:60px;" />
</td><td>
<input name="grdView$ctl08$txtPrice_F" type="text" id="grdView_ctl08_txtPrice_F" class="classPrice" style="width:60px;" />
</td><td>
<input name="grdView$ctl08$txtvat_F" type="text" id="grdView_ctl08_txtvat_F" class="classVat" style="width:60px;" />
</td><td>
<input name="grdView$ctl08$txtTotal_F" type="text" id="grdView_ctl08_txtTotal_F" class="classTotal" style="width:100px;" />
</td><td>
<input name="grdView$ctl08$txtSerial_F" type="text" id="grdView_ctl08_txtSerial_F" class="classSerial" />
</td>
</tr>
</table>
</body>

Use parseFloat on the operands, not on the result of the computation.
For example, replace
obj_tTotal.value = parseFloat(obj_tVat.value + (obj_tPrice.value * obj_tQuantity.value));
with
var tPrice = parseFloat(obj_tPrice.value);
var tQuantity = parseFloat(obj_tQuantity.value);
obj_tTotal.value = tPrice + tPrice * tQuantity;
When you add, like you did, a string and a number, you do a string concatenation.
For example
"1000" + "5" * "100"
gives
"1000" + 500
which is
"1000500"
At this point, it's too late to call parseFloat.

Related

Javascript array and var wont show up when put in script tags

I have a large-ish code that I am working with. My problem is that I have multiple tables/arrays that I'm not sure how to group under one script tag so they all have their own. My tables work okay separately, but I know the code is convoluted. I can't figure out the array. It was supposed to be a 3x5 array, but when it shows up on the page its all one column and one row. Another issue is that when I try to globally declare the array, the text itself shows up in the html rather than executing properly.
<!DOCTYPE html>
<html>
<head>
<title>Door Crash Order Page, v2</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="Expires" content="-1">
<!-- External CSS link -->
<link rel="stylesheet" type="text/css"
href="DoorCrash-ExternalStyles.css">
<script language="javascript">
function add() {
var FoodItems = [
[
document.getElementById('input5'),
document.getElementById('input6'),
document.getElementById('input7')
],
[
document.getElementById('input1'),
document.getElementById('input3'),
document.getElementById('input10')
]
];
var result = [];
for (var i = 0; i < els.length; i++) {
result[result.length] = parseInt(els[0][i].value) -
parseInt(els[1][i].value);
}
alert(result.join(' '));
console.log("FoodItems");
localStorage.setItem("FoodItems", JSON.stringify(FoodItems));
}
window.addEventListener("load", () => {
const ret = localStorage.getItem("FoodItems");
if(!ret) {
alert("retrieval successful");
}
});
<script language="JavaScript"><!--
function cent(amount) {
// returns the amount in the .99 format
return (amount == Math.floor(amount)) ? amount + '.00' : ( (amount*10
== Math.floor(amount*10)) ? amount + '0' : amount);
}
function update(form) {
var subtotal = (form.quantity.value - 0) * (form.unitcost.value - 0)+
(form.quantity1.value - 0) * (form.unitcost1.value - 0)+
(form.quantity2.value - 0) * (form.unitcost2.value - 0)+
(form.quantity3.value - 0) * (form.unitcost3.value - 0);
subtotal = Math.floor(subtotal * 1000)/1000;
form.subtotal.value = '$' + cent(subtotal);
var tax = subtotal / 100 * (form.rate.value - 0);
tax = Math.floor(tax * 1000)/1000;
form.tax.value = '$' + cent(tax);
total = subtotal + tax;
total = Math.floor(total * 1000)/1000;
form.total.value = '$' + cent(total);
}
//--></script>
<h4>Jimmy John's</h4>
<form>
<table>
<tr><td>The Veggie Quantity: </td><td><input type="text" name="quantity"
size="8"></td></tr>
<tr><td>Billy Club Quantity: </td><td><input type="text" name="quantity1"
size="8"></td></tr>
<tr><td>Totally Tuna Quantity: </td><td><input type="text"
name="quantity2" size="8"></td></tr>
<tr><td>Turkey Tom Quantity: </td><td><input type="text" name="quantity3"
size="8"></td></tr>
<tr><td>The Veggie Cost: </td><td><input type="text" name="unitcost"
value="6.99"size="8"></td></tr>
<tr><td>Billy Club Cost: </td><td><input type="text" name="unitcost1"
value="8.09"size="8"></td></tr>
<tr><td>Totally Tuna Cost: </td><td><input type="text" name="unitcost2"
value="9.49"size="8"></td></tr>
<tr><td>Turkey Tom Cost: </td><td><input type="text" name="unitcost3"
value="7.99"size="8"></td></tr>
<tr><td>Tax Rate (%): </td><td><input type="text" name="rate"
value="6"size="8"></td></tr>
<tr><td>Subtotal: </td><td><input type="text" name="subtotal"size="8">
</td></tr>
<tr><td>Order Tax: </td><td><input type="text" name="tax"size="8"></td>
</tr>
<tr><td>Order Total: </td><td><input type="text" name="total"size="8">
</td></tr>
<tr><td> </td><td><input type="button" onClick="update(this.form)"
value="Click Me"></td></tr>
</table>
</form>
<br>
<script language="JavaScript"><!--
function cent(amount) {
// returns the amount in the .99 format
return (amount == Math.floor(amount)) ? amount + '.00' : ( (amount*10 ==
Math.floor(amount*10)) ? amount + '0' : amount);
}
function update(form) {
var subtotal = (form.quantity.value - 0) * (form.unitcost.value - 0)+
(form.quantity1.value - 0) * (form.unitcost1.value - 0)+
(form.quantity2.value - 0) * (form.unitcost2.value - 0)+
(form.quantity3.value - 0) * (form.unitcost3.value - 0);
subtotal = Math.floor(subtotal * 1000)/1000;
form.subtotal.value = '$' + cent(subtotal);
var tax = subtotal / 100 * (form.rate.value - 0);
tax = Math.floor(tax * 1000)/1000;
form.tax.value = '$' + cent(tax);
total = subtotal + tax;
total = Math.floor(total * 1000)/1000;
form.total.value = '$' + cent(total);
}
//--></script>
<h4>Red Robins</h4>
<form>
<table>
<tr><td>Fish and Chips Quantity: </td><td><input type="text"
name="quantity" size="8"></td></tr>
<tr><td>Clucks and Shrimp Quantity: </td><td><input type="text"
name="quantity1" size="8"></td></tr>
<tr><td>Salmon Quantity: </td><td><input type="text" name="quantity2"
size="8"></td></tr>
<tr><td>Cheeseburger Quantity: </td><td><input type="text"
name="quantity3" size="8"></td></tr>
<tr><td>Fish and Chips Cost: </td><td><input type="text" name="unitcost"
value="9.99"size="8"></td></tr>
<tr><td>Clucks and Shrimp Cost: </td><td><input type="text"
name="unitcost1" value="13.29"size="8"></td></tr>
<tr><td>Salmon Cost: </td><td><input type="text" name="unitcost2"
value="12.79"size="8"></td></tr>
<tr><td>Cheeseburger Cost: </td><td><input type="text" name="unitcost3"
value="8.19"size="8"></td></tr>
<tr><td>Tax Rate (%): </td><td><input type="text" name="rate"
value="6"size="8"></td></tr>
<tr><td>Subtotal: </td><td><input type="text" name="subtotal"size="8">
</td></tr>
<tr><td>Order Tax: </td><td><input type="text" name="tax"size="8"></td>
</tr>
<tr><td>Order Total: </td><td><input type="text" name="total"size="8">
</td></tr>
<tr><td> </td><td><input type="button" onClick="update(this.form)"
value="Click Me"></td></tr>
</table>
</form>
<br>
<script language="JavaScript"><!--
function cent(amount) {
// returns the amount in the .99 format
return (amount == Math.floor(amount)) ? amount + '.00' : ( (amount*10 ==
Math.floor(amount*10)) ? amount + '0' : amount);
}
function update(form) {
var subtotal = (form.quantity.value - 0) * (form.unitcost.value - 0)+
(form.quantity1.value - 0) * (form.unitcost1.value - 0)+
(form.quantity2.value - 0) * (form.unitcost2.value - 0)+
(form.quantity3.value - 0) * (form.unitcost3.value - 0);
subtotal = Math.floor(subtotal * 1000)/1000;
form.subtotal.value = '$' + cent(subtotal);
var tax = subtotal / 100 * (form.rate.value - 0);
tax = Math.floor(tax * 1000)/1000;
form.tax.value = '$' + cent(tax);
total = subtotal + tax;
total = Math.floor(total * 1000)/1000;
form.total.value = '$' + cent(total);
}
//--></script>
<h4>Bob Evans </h4>
<form>
<table>
<tr><td>Homestead Breakfast Quantity: </td><td><input type="text"
name="quantity" size="8"></td></tr>
<tr><td>Fruitiful Farmer Quantity: </td><td><input type="text"
name="quantity1" size="8"></td></tr>
<tr><td>Chicken Tenders Quantity: </td><td><input type="text"
name="quantity2" size="8"></td></tr>
<tr><td>Meatloaf Quantity: </td><td><input type="text" name="quantity3"
size="8"></td></tr>
<tr><td>Homestead Breakfast Cost: </td><td><input type="text"
name="unitcost" value="7.99"size="8"></td></tr>
<tr><td>Fruitiful Farmer Cost: </td><td><input type="text"
name="unitcost1" value="8.99"size="8"></td></tr>
<tr><td>Chicken Tenders Cost: </td><td><input type="text" name="unitcost2"
value="11.49"size="8"></td></tr>
<tr><td>Meatloaf Cost: </td><td><input type="text" name="unitcost3"
value="12.99"size="8"></td></tr>
<tr><td>Tax Rate (%): </td><td><input type="text" name="rate"
value="6"size="8"></td></tr>
<tr><td>Subtotal: </td><td><input type="text" name="subtotal"size="8">
</td></tr>
<tr><td>Order Tax: </td><td><input type="text" name="tax"size="8"></td>
</tr>
<tr><td>Order Total: </td><td><input type="text" name="total"size="8">
</td></tr>
<tr><td> </td><td><input type="button" onClick="update(this.form)"
value="Click Me"></td></tr>
</table>
</form>
<br>
<script language="JavaScript"><!--
function cent(amount) {
// returns the amount in the .99 format
return (amount == Math.floor(amount)) ? amount + '.00' : ( (amount*10 ==
Math.floor(amount*10)) ? amount + '0' : amount);
}
function update(form) {
var subtotal = (form.quantity.value - 0) * (form.unitcost.value - 0)+
(form.quantity1.value - 0) * (form.unitcost1.value - 0)+
(form.quantity2.value - 0) * (form.unitcost2.value - 0)+
(form.quantity3.value - 0) * (form.unitcost3.value - 0);
subtotal = Math.floor(subtotal * 1000)/1000;
form.subtotal.value = '$' + cent(subtotal);
var tax = subtotal / 100 * (form.rate.value - 0);
tax = Math.floor(tax * 1000)/1000;
form.tax.value = '$' + cent(tax);
total = subtotal + tax;
total = Math.floor(total * 1000)/1000;
form.total.value = '$' + cent(total);
}
//--></script>
<h4>The Brown Jug</h4>
<form>
<table>
<tr><td>Italian Club Quantity: </td><td><input type="text" name="quantity"
size="8"></td></tr>
<tr><td>Tuna Salad Sandwhich Quantity: </td><td><input type="text"
name="quantity1" size="8"></td></tr>
<tr><td>Parmigiana Sandwhich Quantity: </td><td><input type="text"
name="quantity2" size="8"></td></tr>
<tr><td>Potato Skins Quantity: </td><td><input type="text"
name="quantity3" size="8"></td></tr>
<tr><td>Italian Club Cost: </td><td><input type="text" name="unitcost"
value="9.99"size="8"></td></tr>
<tr><td>Tuna Salad Sanwhich Cost: </td><td><input type="text"
name="unitcost1" value="7.99"size="8"></td></tr>
<tr><td>Parmigiana Sandwhich Cost: </td><td><input type="text"
name="unitcost2" value="8.99"size="8"></td></tr>
<tr><td>Potato Skins Cost: </td><td><input type="text" name="unitcost3"
value="8.50"size="8"></td></tr>
<tr><td>Tax Rate (%): </td><td><input type="text" name="rate"
value="6"size="8"></td></tr>
<tr><td>Subtotal: </td><td><input type="text" name="subtotal"size="8">
</td></tr>
<tr><td>Order Tax: </td><td><input type="text" name="tax"size="8"></td>
</tr>
<tr><td>Order Total: </td><td><input type="text" name="total"size="8">
</td></tr>
<tr><td> </td><td><input type="button" onClick="update(this.form)"
value="Click Me"></td></tr>
</table>
</form>
</head>
<body>
extern double a[3][5];
// Array declaration
function add() {
var FoodItems = [
[
document.getElementById('input5'),
document.getElementById('input6'),
document.getElementById('input7')
],
[
document.getElementById('input1'),
document.getElementById('input3'),
document.getElementById('input10')
]
];
var result = [];
for (var i = 0; i < els.length; i++) {
result[result.length] = parseInt(els[0][i].value) - parseInt(els[1]
[i].value);
}
alert(result.join(' '));
}
<input text="text" value="Resturant Name" id="input5"/>
<input text="text" value="Item Name" id="input6"/>
<input text="text" value="Item price" id="input7"/>
<br>
<input text wrap ="text" value="Jimmy John's" id="input1"/>
<input text wrap="text" value="Billy Club, Turkey Tom, Totally Tuna, The
Veggie" id="input2"/>
<input text="text" value="$8.09, $7.99, $9.49, $6.99 " id="input8"/>
<br>
<input text="text" value="Red Robins" id="input3"/>
<input text="text" value="Fish and Chips, Clucks and Shrimp, Salmon,
Cheeseburger" id="input4"/>
<input text="text" value="$9.99, $13.29, $12.79, $8.19" id="input9"/>
<br>
<input text="text" value="Bob Evans" id="input10"/>
<input text="text" value="Homestead Breakfast, Fruitiful Farmer, Chicken
Tenders, Meatloaf" id="input11"/>
<input text="text" value="$7.99, $8.99, $11.49, $12.99" id="input12"/>
<br>
<input text="text" value="The Brown Jug" id="input13"/>
<input text="text" value="Italian Club, Tuna Salad, Parm Sandwhich, Potato
Skin" id="input14"/>
<input text="text" value="$9.99, $7.99, $8.99, $8.50" id="input15"/>
console.log("FoodItems");
localStorage.setItem("FoodItems", JSON.stringify(FoodItems));
<!-- Header -->
Door Crash Order Page
<hr>
<!-- Menu -->
<div class="menu">
Main Page
Restaurants Page
Order Page
</div>
<hr>
<!-- Form -->
<form
method="get"
enctype="application/x-www-form-urlencoded"
action="http://www.tipjar.com/cgi-bin/test"
>
<label>Name: </label>
<input type="text" name="txtName" required>
<br><br>
<label>Address: </label>
<input type="text" name="txtAddress" required>
<br><br>
<label>Phone: </label>
<input type="tel" name="inpPhone" required>
<br><br>
<fieldset class="fieldsetStyle">
<legend>Restaurant:</legend>
<input type="radio" name="rbRestaurant" value="BobEvans"
class="radioButtonStyle"> Bob Evans<br>
<input type="radio" name="rbRestaurant" value="BrownJug"
class="radioButtonStyle"> Brown Jug<br>
<input type="radio" name="rbRestaurant" value="JimmyJohns"
class="radioButtonStyle"> Jimmy Johns<br>
<input type="radio" name="rbRestaurant" value="RedRobin"
class="radioButtonStyle"> Red Robin<br>
</fieldset>
<br>
<!-- Footer -->
<hr>
Door Crash, 1204 South University Avenue, Ann Arbor, MI 48104, MI
734-761-3355 Copyright © 2019
<hr>
</body>
</html>

How to get Javascript method to print in my HTML

I'm really frustrated trying to get my html and javascript code to work together. I am trying to get the user information from the storeClientData() to print on top of the reservationMessage. I have been working on it for the last 4 hours with no luck. Any help would be much appreciated.
I want to get a output that would show like:
Mr. Firstname, Lastname, street, city, province/state, country, contact info.
Then:
Car size and price, options(ex. navigation), duration in days, cost of rental.
<!DOCTYPE html>
<html>
<head>
<title>Dodgy Brakes Car Rental</title>
<meta charset="utf-8" />
<link href="new.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="processregistration.js"></script>
</head>
<center>
<img src="logo.jpg" height="250" width="auto">
</center>
<body>
<center>
<form name=costEstimation>
<table>
<tr>
<td>
<select required id="honorific">
<option value=None>None</option>
<option value=Mr.>Mr.</option>
<option value=Mrs.>Mrs.</option>
<option value=Ms.>Ms.</option>
<option value=Dr.>Dr.</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="text" pattern ="[a-zA-Z0-9-\s]{2,20}$" placeholder="First Name" id="firstName">
<input type="text" pattern ="[a-zA-Z0-9-\s]{2,20}$" placeholder="Last Name" id="lastName">
</td>
</tr>
<tr>
<td>
<input type="text" pattern="[a-zA-Z0-9-\s]{2,25}" placeholder="Street" id="street">
<input type="text" pattern="[a-zA-Z0-9-\s]{2,25}" placeholder="City" id="city">
</td>
</tr>
<tr>
<td>
<input type="text" pattern="[a-zA-Z0-9-\s]{2,25}" placeholder="State/Province" id="stateProvince">
<input type="text" pattern="[a-zA-Z0-9-\s]{2,25}" placeholder="Country" id="country">
</td>
</tr>
<tr>
<td>
<input type="text" placeholder="Business Number" pattern="\d{3}[\-]\d{3}[\-]\d{4}" id="businessNumber">
<input type="text" placeholder="Home Number" pattern="\d{3}[\-]\d{3}[\-]\d{4}" id="homeNumber">
</td>
</tr>
<tr>
<td>
<input type = "email" pattern = "[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,5}$" placeholder="E-mail" id="emailAddress">
</td>
</tr>
<tr>
<td>
<center>
<input type=button value="Register" onClick="showReservations(); return false;">
<input type = "reset" value = "Reset">
</center>
</td>
</tr>
</table>
<div id="reservations" style="display:none;">
<h3>Reservation Form</h3>
<table>
<tr>
<td>
<center>
<h4><u>Type of Vehicle</u></h4>
<input type=radio name=type value=25>Small $25.00<br>
<input type=radio name=type value=35>Midsize $35.00<br>
<input type=radio name=type value=45>Full-sized $45.00<br>
<input type=radio name=type value=50 >Van $50.00<br>
</center>
</td>
</tr>
<tr>
<td>
<center>
<h4><u>Additional Options</u></h4>
<input type=checkbox name=navigationSystem value= "10" >Navigation System $10.00<br>
<input type=checkbox name=childSeat value="5" >Child Seat $5.00<br>
<input type=checkbox name=roofRack value="15" >Roof Rack $15.00<br>
<input type=checkbox name=bicycleRack value="15" >Bicycle Rack $15.00<br>
</center>
</td>
</tr>
<tr>
<td>
<center>
<br>
<input type="text" placeholder="Enter Days" id="duration">
<input type=button value="Calculate" onClick="calculateRental(); showFinal(); return false;">
</center>
</td>
</tr>
</table>
</div>
<div id="showFinal" style="display:none;">
<h3><span id="reservationResult"; </span></h3>
</div>
</form>
</center>
</body>
</html>
var customerData=[];
function storeClientData(){
var honorific=document.getElementById("honorific").value
customerData[0]=honorific;
var firstName=document.getElementById("firstName").value;
customerData[1]=firstName;
var lastName=document.getElementById("lastName").value;
customerData[2]=lastName;
var street=document.getElementById("street").value;
customerData[3]=street;
var city=document.getElementById("city").value;
customerData[4]=city;
var stateProvince=document.getElementById("stateProvince").value
customerData[5]=stateProvince;
var country=document.getElementById("country").value;
customerData[6]=country;
var businessNumber=document.getElementById("businessNumber").value;
customerData[7]=businessNumber;
var homeNumber=document.getElementById("homeNumber").value;
customerData[8]=homeNumber;
var emailAddress=document.getElementById("emailAddress").value;
customerData[9]=emailAddress;
var customerMessage = (customerData[0] + customerData[1] + " " + customerData[2]
+ "<br>" + customerData[3]
+ "<br>" + customerData[4]
+ "<br>" + customerData[5]
+ "<br>" + customerData[6]
+ "<br>" + customerData[7]
+ "<br>" + customerData[8]
+ "<br>" + customerData[9]);
document.getElementById("customerResult").innerHTML = customerMessage;
setFormToEdit();
}
function calculateRental(){
var carSize = parseFloat(0);
var extraAmount = parseFloat(0);
var totalCost = parseFloat(0);
var message = " ";
var reservationMessage = " ";
var duration = parseFloat(0)
for (x = 0; x<document.costEstimation.type.length; x++){
if(document.costEstimation.type[x].checked){
carSize = document.costEstimation.type[x].value;
}
}
carSize = parseFloat(carSize);
if(document.costEstimation.navigationSystem.checked){
extraAmount += parseFloat(document.costEstimation.navigationSystem.value);
message = (message + " Navigation system");
}if (document.costEstimation.childSeat.checked){
extraAmount += parseFloat(document.costEstimation.childSeat.value);
message = (message + " Child seat");
}if (document.costEstimation.roofRack.checked){
extraAmount += parseFloat(document.costEstimation.roofRack.value);
message = (message + " Roof rack");
}if (document.costEstimation.bicycleRack.checked){
extraAmount += parseFloat(document.costEstimation.bicycleRack.value);
message = (message + " Bicycle rack");
}
duration = (document.getElementById("duration").value);
duration = parseFloat(duration)
totalCost = (duration*carSize)+(duration*extraAmount);
reservationMessage += ("Car Information:" + "<br>" + "Rental cost: " + carSize + "<br>" + "Additional Options: " + message + "<br>" + "Total cost: " + totalCost);
document.getElementById("reservationResult").innerHTML = reservationMessage;
}
function setFormToEdit() {
document.getElementById("honorific").readOnly=false;
document.getElementById("firstName").readOnly=false;
document.getElementById("lastName").readOnly=false;
document.getElementById("street").disabled=false;
document.getElementById("city").readOnly=false;
document.getElementById("stateProvince").readOnly=false;
document.getElementById("country").disabled=false;
document.getElementById("homeNumber").readOnly=false;
document.getElementById("businessNumber").readOnly=false;
document.getElementById("emailAddress").disabled=false;
}
function showReservations() {
document.getElementById("reservations").style.display = "block";
}
function showFinal() {
document.getElementById("showFinal").style.display = "block";
}
var customerData = [];
function storeClientData() {
var honorific = document.getElementById("honorific").value
customerData[0] = honorific;
var firstName = document.getElementById("firstName").value;
customerData[1] = firstName;
var lastName = document.getElementById("lastName").value;
customerData[2] = lastName;
var street = document.getElementById("street").value;
customerData[3] = street;
var city = document.getElementById("city").value;
customerData[4] = city;
var stateProvince = document.getElementById("stateProvince").value
customerData[5] = stateProvince;
var country = document.getElementById("country").value;
customerData[6] = country;
var businessNumber = document.getElementById("businessNumber").value;
customerData[7] = businessNumber;
var homeNumber = document.getElementById("homeNumber").value;
customerData[8] = homeNumber;
var emailAddress = document.getElementById("emailAddress").value;
customerData[9] = emailAddress;
var CarSize = document.querySelector('input[name="type"]:checked').value;
customerData[10] = CarSize;
var prices = document.getElementsByClassName('addtionClass');
var str = "";
for (var i = 0; i < prices.length; i++) {
if (prices[i].checked)
{
str += prices[i].value + ",";
}
}
customerData[11] = str;
var duration = document.getElementById('duration').value;
customerData[12] = duration;
duration = parseFloat(duration)
var customerMessage = (customerData[0] + customerData[1] + " " + customerData[2]
+ "<br>" + customerData[3]
+ "<br>" + customerData[4]
+ "<br>" + customerData[5]
+ "<br>" + customerData[6]
+ "<br>" + customerData[7]
+ "<br>" + customerData[8]
+ "<br>" + customerData[9]
+ "<br>" + customerData[10]
+ "<br>" + customerData[11]
+ "<br>" + customerData[12]
);
calculateRental();
document.getElementById("customerResult").innerHTML = customerMessage;
setFormToEdit();
}
function calculateRental() {
var carSize = parseFloat(0);
var extraAmount = parseFloat(0);
var totalCost = parseFloat(0);
var message = " ";
var reservationMessage = " ";
var duration = parseFloat(0)
for (x = 0; x < document.costEstimation.type.length; x++) {
if (document.costEstimation.type[x].checked) {
carSize = document.costEstimation.type[x].value;
}
}
carSize = parseFloat(carSize);
if (document.costEstimation.navigationSystem.checked) {
extraAmount += parseFloat(document.costEstimation.navigationSystem.value);
message = (message + " Navigation system");
} if (document.costEstimation.childSeat.checked) {
extraAmount += parseFloat(document.costEstimation.childSeat.value);
message = (message + " Child seat");
} if (document.costEstimation.roofRack.checked) {
extraAmount += parseFloat(document.costEstimation.roofRack.value);
message = (message + " Roof rack");
} if (document.costEstimation.bicycleRack.checked) {
extraAmount += parseFloat(document.costEstimation.bicycleRack.value);
message = (message + " Bicycle rack");
}
duration = (document.getElementById("duration").value);
duration = parseFloat(duration)
totalCost = (duration * carSize) + (duration * extraAmount);
reservationMessage += ("Car Information:" + "<br>" + "Rental cost: " + carSize + "<br>" + "Additional Options: " + message + "<br>" + "Total cost: " + totalCost);
document.getElementById("reservationResult").innerHTML = reservationMessage;
}
function setFormToEdit() {
document.getElementById("honorific").readOnly = false;
document.getElementById("firstName").readOnly = false;
document.getElementById("lastName").readOnly = false;
document.getElementById("street").disabled = false;
document.getElementById("city").readOnly = false;
document.getElementById("stateProvince").readOnly = false;
document.getElementById("country").disabled = false;
document.getElementById("homeNumber").readOnly = false;
document.getElementById("businessNumber").readOnly = false;
document.getElementById("emailAddress").disabled = false;
}
debugger;
function showReservations() {
document.getElementById('reservations').style.display = 'block';
}
function showFinal() {
document.getElementById('showFinalResult').style.display = 'block';
}
<html>
<head>
<title>Dodgy Brakes Car Rental</title>
<meta charset="utf-8" />
<link href="new.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="processregistration.js"></script>
</head>
<center>
<img src="logo.jpg" height="250" width="auto">
</center>
<body>
<center>
<form name=costEstimation>
<input type="button" value="Print HTML" onclick="storeClientData(); return false;" />
<div id="customerResult">
</div>
<table>
<tr>
<td>
<select required id="honorific">
<option value=None>None</option>
<option value=Mr.>Mr.</option>
<option value=Mrs.>Mrs.</option>
<option value=Ms.>Ms.</option>
<option value=Dr.>Dr.</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="text" pattern="[a-zA-Z0-9-\s]{2,20}$" placeholder="First Name" id="firstName">
<input type="text" pattern="[a-zA-Z0-9-\s]{2,20}$" placeholder="Last Name" id="lastName">
</td>
</tr>
<tr>
<td>
<input type="text" pattern="[a-zA-Z0-9-\s]{2,25}" placeholder="Street" id="street">
<input type="text" pattern="[a-zA-Z0-9-\s]{2,25}" placeholder="City" id="city">
</td>
</tr>
<tr>
<td>
<input type="text" pattern="[a-zA-Z0-9-\s]{2,25}" placeholder="State/Province" id="stateProvince">
<input type="text" pattern="[a-zA-Z0-9-\s]{2,25}" placeholder="Country" id="country">
</td>
</tr>
<tr>
<td>
<input type="text" placeholder="Business Number" pattern="\d{3}[\-]\d{3}[\-]\d{4}" id="businessNumber">
<input type="text" placeholder="Home Number" pattern="\d{3}[\-]\d{3}[\-]\d{4}" id="homeNumber">
</td>
</tr>
<tr>
<td>
<input type="email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,5}$" placeholder="E-mail" id="emailAddress">
</td>
</tr>
<tr>
<td>
<center>
<input type=button value="Register" onclick="showReservations(); return false;">
<input type="reset" value="Reset">
</center>
</td>
</tr>
</table>
<div id="reservations" style="display:none;">
<h3>Reservation Form</h3>
<table>
<tr>
<td>
<center>
<h4><u>Type of Vehicle</u></h4>
<input type=radio name="type" value=25>Small $25.00<br>
<input type=radio name="type" value=35>Midsize $35.00<br>
<input type=radio name= "type" value=45>Full-sized $45.00<br>
<input type=radio name="type" value=50>Van $50.00<br>
</center>
</tr></td>
<tr>
<td>
<center>
<h4><u>Additional Options</u></h4>
<input type=checkbox class="addtionClass" name=navigationSystem value="10">Navigation System $10.00<br>
<input type=checkbox class="addtionClass" name=childSeat value="5">Child Seat $5.00<br>
<input type=checkbox class="addtionClass" name=roofRack value="15">Roof Rack $15.00<br>
<input type=checkbox class="addtionClass" name=bicycleRack value="15">Bicycle Rack $15.00<br>
</center>
</tr></td>
<tr>
<td>
<center>
<br>
<input type="text" placeholder="Enter Days" id="duration">
<input type=button value="Calculate" onclick="calculateRental(); showFinal(); return false;">
</center>
</table>
</div>
<div id="showFinalResult" style="display:none;">
<h3><span id="reservationResult" > </span></h3>
</div>
</form>
</center>
</body>
</html>
You didn't add id="customerResult" attribute in HTML and also you didn't invoke storeClientData() function from HTML. That's the reason why you couldn't get user information from storeClientData() function and couldn't print it top of the reservation form.
I added <input type=button value="storeClientData" onClick="storeClientData(); return false;"> element before registeration button element in HTML and <div id="customerResult"></div> element top of the reservation form.
You can refer final code in jsfiddle link http://jsfiddle.net/ADukg/10171/.

Sum two highest values using reverse() javascript

How do I sum the two highest values from a list of inputs using JavaScript?
I've tried the below, but I get 4 instead of 5:
<table id="tableID">
<tr>
<td> <input name="name" class="compulsory1" type="text" value="1" /> </td>
<td> <input name="name1" class="compulsory1" type="text" value="3" /> </td>
<td> <input name="name2" class="compulsory1" type="text" value="2" /> </td>
<td>
<script type="text/javascript">
var tdsCompulsory = document.getElementsByClassName('compulsory1');
var len = tdsCompulsory.length;
var cDatax = [];
var cData = cDatax.reverse();
sum = 0;
for(var i = 0; i < 2; i++){
cData.push(tdsCompulsory[i].value);
sum += +tdsCompulsory[i].value;
}
alert (sum);
</script>
</td>
</tr>
</table>
First you find the two highest values, and then sum them together. I'd probably do it something like this:
document.getElementById("the-button").onclick = function() {
// Get the values as numbers
var values = Array.prototype.map.call(
document.getElementsByClassName('compulsory1'),
function(input) {
return +input.value; // + converts to number
}
);
// Put them in order *highest* to *lowest*
values.sort(function(left, right) {
return right - left;
});
// Add the first two
var result = values[0] + values[1];
console.log(values[0] + " + " + values[1] + " = " + result);
};
<input name="name" class="compulsory1" type="text" value="1" />
<input name="name1" class="compulsory1" type="text" value="3" />
<input name="name2" class="compulsory1" type="text" value="2" />
<input id="the-button" type="button" value="Run">
More about that Array.prototype.map.call thing in this answer about looping through arrays and array-like things.
But if you specifically want to use reverse, you'd do that after the sort:
document.getElementById("the-button").onclick = function() {
// Get the values as numbers
var values = Array.prototype.map.call(
document.getElementsByClassName('compulsory1'),
function(input) {
return +input.value; // + converts to number
}
);
// Put them in order lowest to highest
values.sort(function(left, right) {
return left - right;
});
// Then reverse that
values.reverse();
// Add the first two
var result = values[0] + values[1];
console.log(values[0] + " + " + values[1] + " = " + result);
};
<input name="name" class="compulsory1" type="text" value="1" />
<input name="name1" class="compulsory1" type="text" value="3" />
<input name="name2" class="compulsory1" type="text" value="2" />
<input id="the-button" type="button" value="Run">
You could try something like following:
function PickTwoHighestCtrl() {
let els = document.querySelectorAll(".compulsory1");
let values = Array.prototype.map.call(els, (el) => {
return Number(el.value) || 0;
});
let highest = Math.max.apply(Math, values);
let secondHighest = Math.max.apply(
Math, values.filter(e => e !== highest)
);
console.log("Two highest values are:", highest, secondHighest, "and their sum is", highest + secondHighest)
}
document.addEventListener("DOMContentLoaded", PickTwoHighestCtrl);
<input class="compulsory1" type="text" value="1" />
<input class="compulsory1" type="text" value="3" />
<input class="compulsory1" type="text" value="2" />
Check this fiddle
<html>
<head>
<script>
var tdsCompulsory = document.getElementsByClassName('compulsory1');
var cDatax = [];
sum = 0;
for(var i = 0; i < 3; i++){
cDatax.push(tdsCompulsory[i].value);
}
// let's convert it to a real array of numbers, not of strings :
var intArray = cDatax.map(Number);
var max = Math.max.apply(null, intArray);
// now let's sort it and take the second element :
var second = intArray.sort(function(a,b){return b-a})[1];
var sum = max+second;
alert(sum)
</script>
</head>
<body>
<table id="tableID">
<tr>
<td> <input name="name" class="compulsory1" type="text" value="1" /> </td>
<td> <input name="name1" class="compulsory1" type="text" value="3" /> </td>
<td> <input name="name2" class="compulsory1" type="text" value="2" /> </td>
<td>
</td>
</tr>
</table>
</body>
</html>
You can try something like this:
Steps
Get all elements
Get their values. Note, since you expect values to be number, yuo should parse them as well.
Sort value array in descending order instead of .sort + .reverse
Calculate your sum
Sample
// Get all elements
var tdsCompulsory = document.getElementsByClassName('compulsory1');
// Get values from all elements
var valArr = Array.prototype.map.call(tdsCompulsory, function(el) {
return parseInt(el.value)
});
// Sort value array in descending order
var cDatax = valArr.sort(function(a, b) {
return b-a
});
var sum = cDatax[0] + cDatax[1];
console.log(sum)
<table id="tableID">
<tr>
<td>
<input name="name" class="compulsory1" type="text" value="1" />
</td>
<td>
<input name="name1" class="compulsory1" type="text" value="3" />
</td>
<td>
<input name="name2" class="compulsory1" type="text" value="2" />
</td>
</tr>
</table>
var tdsCompulsory = document.getElementsByClassName('compulsory1'),
cDatax = Array.prototype.map.call(tdsCompulsory, function(el) {
return parseInt(el.value) || 0;
}),
sum = 0;
cDatax
.sort(function(a, b){
return a - b;
})
.reverse();
sum = cDatax[0] + cDatax[1];
console.log(sum);
<table id="tableID">
<tr>
<td><input name="name" class="compulsory1" type="text" value="1" /></td>
<td><input name="name1" class="compulsory1" type="text" value="3" /></td>
<td><input name="name2" class="compulsory1" type="text" value="2" /></td>
</tr>
</table>

calculate form values from radio group

Trying to calculate a selection value from a radio group and values from other fields. Any 'Name' input adds a value to the Total. I need the value from the radio group to be added to that total.
Here is the HTML:
<FORM NAME="testauthorization" ACTION="" METHOD=POST id="exhibitreg">
<table>
<tr>
<td><label>
<input type="radio" name="sponsorship" value="3000" id="sponsor1" />
$3,000</label>
<br />
<label>
<input type="radio" name="sponsorship" value="1500" id="sponsor2" />
$1,500</label>
<br />
<label>
<input type="radio" name="sponsorship" value="1000" id="sponsor3" />
$1,000</label>
<br /></td>
</tr>
<tr>
<td>Name 1 <INPUT NAME="Name_1" TYPE="TEXT" id="name1" onchange="updatecost(1, 50)" onkeyup="updatecost(1, 50)" VALUE="" size="30"></td>
<td><INPUT NAME="cost_1" TYPE="TEXT" VALUE="" size="4" id="cost1"></td>
</tr>
<tr>
<td>Name 2<INPUT NAME="Name_2" TYPE="TEXT" id="name2" onchange="updatecost(2, 50)" onkeyup="updatecost(2, 50)" VALUE="" size="30"></td>
<td><INPUT NAME="cost_2" TYPE="TEXT" VALUE="" size="4" id="cost2"></td>
</tr>
<tr>
<td>Name 3<INPUT NAME="Name_3" TYPE="TEXT" id="name3" onchange="updatecost(3, 50)" onkeyup="updatecost(3, 50)" VALUE="" size="30"></td>
<td><INPUT NAME="cost_3" TYPE="TEXT" VALUE="" size="4" id="cost3"></td>
</tr>
<tr>
<td colspan="4">Total:
<INPUT NAME="Total" id="Total" TYPE="TEXT" VALUE="" size="8" onFocus="this.form.elements[0].focus()" >
<INPUT TYPE="HIDDEN" onchange="totalcost()" onkeyup="totalcost()"></td>
</tr>
</table>
<INPUT TYPE="SUBMIT" VALUE="Submit">
<input type="RESET" name="Reset" value="Reset" />
</FORM>
And here is the JS:
<script language="JavaScript" type="text/javascript">
function getRadioValue(name) {
var group = document.getElementsByName('sponsorship');
for (var i=0;i<group.length;i++) {
if (group[i].checked) {
return group[i].value;
}
}
return '';
}
function updatecost(num, dollars) {
var text = document.getElementById("name" + num);
var cost = document.getElementById("cost" + num);
if (!text) return;
if (!cost) return;
if (text.value == "") {
cost.value = "";
}
else {
cost.value = dollars;
}
totalcost();
}
function totalcost() {
var total = 0;
for (var i = 1; i <= 3; i++) {
var cost = document.getElementById("cost" + i);
if (cost.value) total += Number(cost.value);
}
document.getElementById("Total").value = total;
}
//-->
</script>
What am I missing? By the way, in case it is not clear, I am a JS novice, so I fully accept criticism that helps me understand a more fundamental error in my approach. Simple is best for me: ;-) Thank you in advance.
Change below function in place of existing
function updatecost(num, dollars) {
var text = document.getElementById("name" + num);
var cost = document.querySelector('input[name="sponsorship"]:checked');
if (!text) return;
if (!cost) return;
totalcost(cost);
}
function totalcost(cost) {
var total = 0;
for (var i = 1; i <= 3; i++) {
var text1 = document.getElementById("name" + i);
if (text1.value != "") total += Number(cost.value);
}
document.getElementById("Total").value = total;
}

performance problem looping through table rows

I am using jquery to loop through table rows and save the data. If the table has 200 rows it is performing slow. I am getting the javascript message "Stop Running this script" in IE when I call this method. Following is the code I am using to loop through table rows. Can you please let me know if there is a better way to do this.
function SaveData() {
var $table = $('#' + gridid);
var rows = $table.find('tbody > tr').get();
var transactions = [];
var $row, empno, newTransaction, $rowChildren;
$.each(rows, function(index, row) {
$row = $(row);
$rowChildren = $row.children("td");
if ($rowChildren.find("input[id*=hRV]").val() === '1') {
empno = $rowChildren.find("input[id*=tEmpno]").val();
newTransaction = new Array();
newTransaction[0] = company;
newTransaction[1] = $rowChildren.find("input[id*=tEmpno]").val();
newTransaction[2] = $rowChildren.find("input[id*=tPC]").val();
newTransaction[3] = $rowChildren.find("input[id*=hQty]").val();
newTransaction[4] = $rowChildren.find("input[id*=hPR]").val();
newTransaction[5] = $rowChildren.find("input[id*=tJC]").val();
newTransaction[6] = $rowChildren.find("input[id*=tL1]").val();
newTransaction[7] = $rowChildren.find("input[id*=tL2]").val();
newTransaction[8] = $rowChildren.find("input[id*=tL3]").val();
newTransaction[9] = $rowChildren.find("input[id*=tL4]").val();
newTransaction[10] = $rowChildren.find("input[id*=tL5]").val();
newTransaction[11] = $rowChildren.find("input[id*=tL6]").val();
newTransaction[12] = $rowChildren.find("input[id*=tL7]").val();
newTransaction[13] = $rowChildren.find("input[id*=tL8]").val();
newTransaction[14] = $rowChildren.find("input[id*=tL9]").val();
newTransaction[15] = $rowChildren.find("input[id*=tL10]").val();
newTransaction[16] = $rowChildren.find("input[id*=tSF]").val();
newTransaction[17] = $rowChildren.find("input[id*=tCG]").val();
newTransaction[18] = $rowChildren.find("input[id*=tTF]").val();
newTransaction[19] = $rowChildren.find("input[id*=tWK]").val();
newTransaction[20] = $rowChildren.find("input[id*=tAI]").val();
newTransaction[21] = $rowChildren.find("input[id*=tWC]").val();
newTransaction[22] = $rowChildren.find("input[id*=tPI]").val();
newTransaction[23] = "E";
var record = newTransaction.join(';');
transactions.push(record);
}
});
if (transactions.length > 0) {
var strTransactions = transactions.join('|');
//send data to server
//here ajax function is called to save data.
}
}
The html structure for the table row is like this
<tr class="rgRow" id="ctl00_c_PETV2_1_gB_ctl00__12">
<td>
Delete
</td><td>
<input type="text" value='385 ' id="tEmpno" />
<input name="ctl00$c$PETV2_1$gB$ctl00$ctl28$hRV" type="hidden" id="ctl00_c_PETV2_1_gB_ctl00_ctl28_hRV" value="1" />
<input name="ctl00$c$PETV2_1$gB$ctl00$ctl28$hRC" type="hidden" id="ctl00_c_PETV2_1_gB_ctl00_ctl28_hRC" value="0" />
</td><td style="width:100px;">
<input type="text" value='Barron, Pamela J.' id="tEE" readonly="readonly" />
</td><td>
<input type="text" value='OT ' id="tPC" />
</td><td>
<input type="text" value='7.00' id="tQty" class="right" />
<input type="hidden" name="ctl00$c$PETV2_1$gB$ctl00$ctl28$hQty" id="ctl00_c_PETV2_1_gB_ctl00_ctl28_hQty" value="7.00000" />
</td><td>
<input type="text" value='22.00' id="tPR" class="right" />
<input type="hidden" name="ctl00$c$PETV2_1$gB$ctl00$ctl28$hPR" id="ctl00_c_PETV2_1_gB_ctl00_ctl28_hPR" value="22.000000" />
</td><td>
<input type="text" value='231.00' id="tAmt" class="right" readonly="readonly" />
</td><td>
<input type="text" value='300 ' id="tJC" />
</td><td>
<input type="text" value='50 ' id="tL1" />
</td><td>
<input type="text" value='23 ' id="tL2" />
</td><td>
<input type="text" value='001 ' id="tL3" />
</td><td>
<input type="text" value=' ' id="tL4" />
</td><td>
<input type="text" value='1 ' id="tSF" />
</td><td>
<input type="text" value='1' id="tCG" />
</td><td>
<input type="text" value='B' id="tTF" />
</td><td>
<input type="text" value='0' id="tWk" />
</td><td>
<input type="text" value='Y' id="tAI" />
</td><td>
<input type="text" value='8810 ' id="tWC" />
</td><td style="width:50px;">
<input type="text" value='' id="tPI" />
</td>
</tr>
Try minimizing your use of jQuery find(). Its performance is really bad on older browsers. Perhaps use good old getElementsByTagName() instead, which is implemented natively even on IE6. Pseudocode:
get list of tr elements;
for each tr element:
get list of input elements descending from current tr element;
for each input:
if input.id matches x
if input.id matches y
if input.id matches z
Hope this helps.
Replace the repeated calls to find by splitting out that part of the id and then doing a var index = $.inArray(idFragment, ['', 'tEmpno', 'hQty']); call or similar strategy to determine the input's position in the transaction array.
Make as few searches on the DOM as possible. Prefer |= over *= selectors if possible.
Or, if possible, modify the serialize function in jQuery as needed and use the index of the input to determine its position in the transaction array.

Categories

Resources