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;
}
Related
I am trying to highlight a value in a div that is the lowest value in an array.
When the user completes each input row (design outlet and actual outlet) the outletIndex() function is called which calculates the percentage and pushes the value into an array. This part I have working.
Then what I am trying to do is find the lowest number in that array and highlight the div (proportion). I want this to be dynamic so as the user completes each input row the percentage is calculated and the lowest index value is highlighted progressively.
I am using querySelectorAll() to match the div class value to the lowest index value but Im not sure if I need to parse a nodeList to match the value of the indexArray?
I am also wondering that if a mistake is typed into the fields and added to the Index array and it happens to be the lowest index it wont match the index values that are shown on the HTML and not call the function.
document.querySelector('#outlet_actual_1').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
let actual = document.getElementById("outlet_actual_1").valueAsNumber || 0;
let design = document.getElementById("outlet_design_1").valueAsNumber || 0;
let result1 = outletIndex(actual, design);
if (!isNaN(result1)) {
document.getElementById("percentage").textContent = `${result1.toFixed(1)}%`;
}
}
});
document.querySelector('#outlet_actual_2').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
let actual = document.getElementById("outlet_actual_2").valueAsNumber || 0;
let design = document.getElementById("outlet_design_2").valueAsNumber || 0;
let result1 = outletIndex(actual, design);
if (!isNaN(result1)) {
document.getElementById("percentage2").textContent = `${result1.toFixed(1)}%`;
}
}
});
document.querySelector('#outlet_actual_3').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
let actual = document.getElementById("outlet_actual_3").valueAsNumber || 0;
let design = document.getElementById("outlet_design_3").valueAsNumber || 0;
let result1 = outletIndex(actual, design);
if (!isNaN(result1)) {
document.getElementById("percentage3").textContent = `${result1.toFixed(1)}%`;
}
}
});
const indexArray = [];
function outletIndex(a, b) {
let result = a / b * 100;
if (!isNaN(result)) {
indexArray.push(+result.toFixed(2));
indexFindandHighlight();
}
console.log(indexArray, result);
return result;
}
function indexFindandHighlight(){
const lowestIndex = Math.min(...indexArray);
const indexCheck = document.querySelectorAll('.proportion').valueAsNumber || 0;
console.log(lowestIndex);
if (lowestIndex == indexCheck) {
$(document).ready(function() {
$("#outlet_actual_1", "#outlet_actual_2", "#outlet_actual_3").onchange(function(){
$(".proportion").effect( "highlight", {color:"#669966"}, 3000 );
});
});
}
};
<table>
<tr>
<div class="form-group row 1" id="outlets1">
<td><label
>Outlet Design</label>
<input
name = "outlet 1 design"
class="form-control design_1"
id="outlet_design_1"
type="number"
placeholder="Outlet 1 Design"
onkeydown="outletIndex();"
/>
</td>
<td><label
>Outlet Actual</label>
<input
name="outlet 1 actual"
class="form-control actual_1"
id="outlet_actual_1"
type="number"
placeholder="Outlet 1 Actual"
onkeydown="outletIndex();"
/>
</td>
<td><label
>Outlet Balance</label>
<input
name="outlet_balance"
class="form-control"
input value=""
id="outlet_balance_1"
type="text"
placeholder="Outlet 1 Balance"
/>
</td><td>
<div class="proportion" id="percentage">
</div>
</td>
</div>
</tr>
<tr>
<div class="form-group row 2" id="outlets2">
<td>
<input
name="outlet_design"
class="form-control design_2"
id="outlet_design_2"
type="number"
placeholder="Outlet 2 Design"
onkeydown="outletIndex();"
/>
</td>
<td>
<input
name="outlet_actual"
class="form-control actual_2"
id="outlet_actual_2"
type="number"
placeholder="Outlet 2 Actual"
onkeydown="outletIndex();"
/>
</td>
<td>
<input
name="outlet_balance"
class="form-control"
id="outlet_balance_2"
type="number"
placeholder="Outlet 2 Balance"
/>
</td><td>
<div class="proportion" id="percentage2">
</div>
</td>
</div></tr>
<tr>
<div class="form-group row 3" id="outlets3">
<td>
<input
name="outlet_design"
class="form-control design_3"
id="outlet_design_3"
type="number"
placeholder="Outlet 3 Design"
onkeydown="outletIndex();"
/>
</td>
<td>
<input
name="outlet_actual"
class="form-control actual_3"
id="outlet_actual_3"
type="number"
placeholder="Outlet 3 Actual"
onkeydown="outletIndex();"
/>
</td>
<td>
<input
name="outlet_balance"
class="form-control"
id="outlet_balance_3"
type="number"
placeholder="Outlet 3 Balance"
/>
</td><td>
<div class="proportion" id="percentage3">
</div>
</td>
</div></tr>
</div>
</table>
</fieldset>
</form>
</div>
Multiple issues:
Clean up HTML
Reuse code
Consistency, Either use jquery or javascript
Separate UI changes from data change.
Consistency, Bind event listener either using HTML or javascript file.
Please check below sample
const number = (str) => Number(str) || 0;
const bind = (id) => {
function onBind(e) {
let actual = number(document.querySelector(`#outlet_actual_${id}`).value);
let design = number(document.querySelector(`#outlet_design_${id}`).value);
let result1 = percentage(actual, design);
if (!isNaN(result1)) {
document.querySelector(
`#percentage_${id}`
).textContent = `${result1.toFixed(1)}%`;
}
updateIndex(id, result1);
highlight();
}
document
.querySelector(`#outlet_actual_${id}`)
.addEventListener("change", onBind);
document
.querySelector(`#outlet_design_${id}`)
.addEventListener("change", onBind);
};
function percentage(a, b) {
return b === 0 ? 0 : (a / b) * 100;
}
let percentages = [];
function updateIndex(id, value) {
percentages[id - 1] = value;
}
function highlight() {
let minIndex = -1;
let minValue = Number.MAX_SAFE_INTEGER;
for (let index in percentages) {
if (percentages[index] < minValue) {
minIndex = Number(index);
minValue = percentages[index];
}
}
if (minIndex === -1) return;
document.querySelector(`#percentage_${minIndex + 1}`).style.color = "red";
setTimeout(() => {
document.querySelector(`#percentage_${minIndex + 1}`).style.color = "black";
}, 3000);
}
bind(1);
bind(2);
bind(3);
<table>
<tr>
<div class="form-group row 1" id="outlets1">
<td><label
>Outlet Design</label>
<input
name = "outlet 1 design"
class="form-control design_1"
id="outlet_design_1"
type="number"
placeholder="Outlet 1 Design"
/>
</td>
<td><label
>Outlet Actual</label>
<input
name="outlet 1 actual"
class="form-control actual_1"
id="outlet_actual_1"
type="number"
placeholder="Outlet 1 Actual"
/>
</td>
<td><label
>Outlet Balance</label>
<input
name="outlet_balance"
class="form-control"
input value=""
id="outlet_balance_1"
type="text"
placeholder="Outlet 1 Balance"
/>
</td><td>
<div class="proportion" id="percentage_1">
</div>
</td>
</div>
</tr>
<tr>
<div class="form-group row 2" id="outlets2">
<td>
<input
name="outlet_design"
class="form-control design_2"
id="outlet_design_2"
type="number"
placeholder="Outlet 2 Design"
/>
</td>
<td>
<input
name="outlet_actual"
class="form-control actual_2"
id="outlet_actual_2"
type="number"
placeholder="Outlet 2 Actual"
/>
</td>
<td>
<input
name="outlet_balance"
class="form-control"
id="outlet_balance_2"
type="number"
placeholder="Outlet 2 Balance"
/>
</td><td>
<div class="proportion" id="percentage_2">
</div>
</td>
</div></tr>
<tr>
<div class="form-group row 3" id="outlets3">
<td>
<input
name="outlet_design"
class="form-control design_3"
id="outlet_design_3"
type="number"
placeholder="Outlet 3 Design"
/>
</td>
<td>
<input
name="outlet_actual"
class="form-control actual_3"
id="outlet_actual_3"
type="number"
placeholder="Outlet 3 Actual"
/>
</td>
<td>
<input
name="outlet_balance"
class="form-control"
id="outlet_balance_3"
type="number"
placeholder="Outlet 3 Balance"
/>
</td><td>
<div class="proportion" id="percentage_3">
</div>
</td>
</div></tr>
</div>
</table>
</fieldset>
</form>
</div>
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/.
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>
Hello I need to sum the values of same class input in one input with class name total.
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="total" value="" />
Possible?
A working fiddle here
$(document).on("change", "qty1", function() {
var sum = 0;
$("input[class *= 'qty1']").each(function(){
sum += +$(this).val();
});
$(".total").val(sum);
});
You pretty much had it, just needed to adjust your JQuery a little bit for the appropriate selectors
updated fiddle : http://jsfiddle.net/5gsBV/7/
$(document).on("change", ".qty1", function() {
var sum = 0;
$(".qty1").each(function(){
sum += +$(this).val();
});
$(".total").val(sum);
});
I suggest this solution:
html
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="total" value="" />
<div id="result"></div>
js
$(".qty1").on("blur", function(){
var sum=0;
$(".qty1").each(function(){
if($(this).val() !== "")
sum += parseInt($(this).val(), 10);
});
$("#result").html(sum);
});
fiddle
I think your issue is here:
$("#destination").val(sum);
change it to:
$(".total").val(sum);
And instead of change event i suggest you to use keyup instead.
$(document).on("keyup"
$(document).on("keyup", ".qty1", function() {
var sum = 0;
$(".qty1").each(function(){
sum += +$(this).val();
});
$(".total").val(sum);
});
We can use following own function
(function( $ ){
$.fn.sum=function () {
var sum=0;
$(this).each(function(index, element){
sum += parseFloat($(element).val());
});
return sum;
};
})( jQuery );
//Call $('.abcd').sum();
http://www.gleegrid.com/code-snippet/javascript/jquery-sum-input-values-by-class/?filter=bygroup&group=JQuery
$('.qty1').each(function(){
sum += parseFloat(this.value);
});
console.log(sum);
This will work with pure js
<input type="text" value=" " class="percent-input"> <br>
<input type="text" value=" " class="percent-input"> <br>
<input type="text" value=" " class="percent-input"> <br>
<p>Total Value :<span id="total">100%</span></p>
<p>Left Value :<span id="left">0.00%</span></p>
var percenInput = document.querySelectorAll('.percent-input');
for (let i = 0; i < percenInput.length; i++) {
percenInput[i].addEventListener('keyup', getPercentVal)
}
function getPercentVal() {
var total = 0;
var allPercentVal = document.querySelectorAll('.percent-input');
for (var i = 0; i < allPercentVal.length; i++) {
if (allPercentVal[i].value > 0) {
var ele = allPercentVal[i];
total += parseFloat(ele.value);
}
}
document.getElementById("total").innerHTML = total.toFixed(2) + '%';
document.getElementById("left").innerHTML = (100 - total).toFixed(2) + '%';
}
You almost had it:
$(document).on("change", ".qty1", function() {
var sum = 0;
$(".qty1").each(function(){
sum += +$(this).val();
});
$(".total").val(sum);
});
http://jsfiddle.net/DUKL6/1
The problem with all of the above answers is that they fail if you enter something other than a number. If you want something that is more friendly to users, you should do some validation, perhaps even give some feedback when a value other than a number is entered.
$('body').on('change', '.qty1', function() {
var total=0;
$(".qty1").each(function(){
quantity = parseInt($(this).val());
if (!isNaN(quantity)) {
total += quantity;
}
});
$('.total').val('Total: '+total);
});
<input type="text" class="price" placeholder="enter number one" />
<input type="text" class="price" placeholder="enter number two" />
<input type="text" class="price" placeholder="enter number three" />
<input type="text" class="price" placeholder="enter number four" />
<input type="text" id="total">
<script>
$(document).ready( function() {
$(document).on("keyup", ".price", function() {
var sum = 0;
$(".price").each(function(){
sum += +$(this).val();
});
$('#total').val(sum);
});
});
</script>
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.