I'm trying to write a piece of code that is supposed to keep a running total. More specifically what I would like it to do is, every time you click the button to add the sub total to the total, it should keep adding into the subtotal. The way the whole thing works now is, there is three meal items to choose from in a dropdown that each have their own price. When a food item is selected, the user types in how many of that item they want. Then user clicks the add to total button to add the food item to one text field. Under that field is a span that shows the grand total after a $3.50 delivery charge is added on. The span is where I want the running total to keep adding the sum every time the button is clicked. I am new to Javascript so I've been trying my best. I've also looked at topics here on SO to see if I can find something similar to my issue and I've seen some that are close but not quite what I'm looking for. Here"s my code...
<script>
function myTotal()
{
var meals = document.getElementById("foodItems").value;
var howMany = document.getElementById("itemTotal").value;
var shippingCost = "3.50";
var totalBill = parseFloat(meals) * howMany + parseFloat(shippingCost);
var addingTotal = parseFloat(meals) * howMany;
var runTotal = document.getElementById("runningTotal").value;
if (isNaN(totalBill)) { // Cash calculator
document.getElementById("total").value = "Invalid amount"
//alert("result of isNaN" ); //The input amount is a non numeric string. It is or contains letters and/or spaces
}
else { //adds total to the sub total field
document.getElementById("total").value = "$" + parseFloat(addingTotal).toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
//Convert input value into a floating point number. toFixed() requires a number value to work with
}//end Cash Calculator
var i = ""; //This piece is where I'm trying to begin the running total
if(i=totalBill, i=howMany*totalBill, i++ ){//adds delivery charge + subtotal. But doesn't keep a running total
document.getElementById("runningTotal").innerHTML = parseFloat(totalBill).toFixed(2);
}
else {
document.getElementById("runningTotal").innerHTML = parseFloat(i++) * howMany;
}
}
</script>
<form id="survey" name="survey" method="get" action="formHandler.php" class="col-4">
<!-- enter your forms code below -->
<div id="fieldset">
<legend>Place an Order!</legend>
<h3>There is a $3.50 delivery fee</h3>
<fieldset>
<label for="foodItems">Quick Meal Food Items</label>
<select name="foodItems" id="foodItems">
<option value="6.00">Pepperoni Pizza - $6.00</option>
<option value="3.00">Bacon BBQ Burger - $3.00</option>
<option value="8.00">Steak and Eggs - $8.00</option>
</fieldset>
<!--The "input" element has "required" in the parameters so the user must fill out all fields but the email.-->
<fieldset>
<input type="text" name="itemTotal" id="itemTotal" size="25" required>How Many Orders?(Limit To 5 per Meal Type)</input>
</fieldset>
<fieldset>
<input type="button" name="click" id="button" value="Add to Order" onClick="myTotal()">
<input type="text" name="total" id="total" size="25">Grand Total</input>
<br>
<span id="runningTotal"></span> <!--runningTotal span-->
</fieldset>
<label for="name">Name: (First, Last)</label>
<input type="text" name="name" id="name" size="25" required></input>
<label for="Address">Address</label>
<input type="text" name="Address" id="address" size="25" required></input>
<label for="email">Email</label>
<input type="email" name="email" id="email" size="40" maxlength="40"></input>
<br><br>
<label for="checkbox">Sign me up for deals via email</label>
<input type="checkbox" name="checkbox" id="checkbox" value="Signup" checked="checked"></input>
<input type="submit" method="post" value="Submit" class="button"/>
<input type="reset" value="Reset" class="button"/>
</form>
</div>
Any help would be awesome! Please address any confusion please. I want to be as clear as possible to try to get the best help for me and others here on SO. I also hope my question isn't off topic. Like I said, I tried to find something pertaining to this here on SO. Thank you so much!
Do you mean something like this? (jsfiddle here)
function myTotal()
{
// Error checking removed....
// Calculate cost of current item
var itemSelect = document.getElementById("foodItems");
var mealCost = parseFloat(itemSelect.value);
var howMany = parseInt(document.getElementById("itemTotal").value);
var thisItemCost = mealCost * howMany;
var shippingCost = 3.5;
// Get running total from the "total" text box
var runTotal = parseFloat(document.getElementById("total").value);
// Only add shipping cost once
if (isNaN(runTotal) || 0 == runTotal) runTotal = shippingCost;
// Add this item to total and update "total" text box
document.getElementById("total").value = (thisItemCost + runTotal).toFixed(2);
// Add item to span
document.getElementById("runningTotal").innerHTML += "</br>" +
itemSelect.options[itemSelect.selectedIndex].innerHTML +
" x " + howMany +
" .... $" + thisItemCost.toFixed(2);
}
Related
I am trying to get this calculated field to pull from multiple forms (15 to be exact) and display a grand total. As of now I can't get anything to show up in the field box. Any help is greatly appreciated!
<script type="text/javascript">
function update()
{
var form = document.forms[0];
var sum = eval(form.sum.value) + eval(form.sum.value);
form.sum.value = isNaN(sum,'all') ? "" : sum;
}
</script>
<form name="form0" onsubmit="false">
<fieldset>
<legend>Pledge Total (total before tax & shipping)</legend>
<label for="f1">Total ($)</label>
<input id="f2" name="sum" readonly="readonly">
</fieldset>
</form>
I am trying to get the values from 3 html text fields and add them together to get the total value when the use clicks on the button. I am new to javascript and after researching online, I found an example code and implemented to my code, but it is not showing any values. Here is my code:
<form name="selectVehicleForm" action="SelectVehicle">
Car Make: <input type="text" name="make" id="make" value="${Vehicles.make}" disabled> <br>
Car Model: <input type="text" name="model" id="model" value="${Vehicles.model}" disabled> <br>
Car Year: <input type="text" name="year" id="year" value="${Vehicles.year}" disabled> <br>
Car Transmission: <input type="text" name="transmission" id="transmission" value="${Vehicles.transimssion}" disabled> <br>
Car Rate Per Mile: <input type="text" name="rpm" id="rpm" value="${Vehicles.ratePerMile}" disabled> <br>
Car Rate: <input type="text" name="rpd" id="rpd" value="${Vehicles.ratePerDay}" disabled> <br>
<%
int id = (Integer) request.getAttribute("id");
%>
<input type="hidden" name="id" value="<%=id%>">
Pick Up Date: <input type="date" name="pickUpDate"> <br>
Return Date: <input type="date" name="returnDate"> <br>
Total Miles: <input type="text" name="totalMile" id="totalMile" placeholder="approximate"> <br> <br>
<script>
function totalDue(){
var rpm = document.getElementById("rpm").value;
var rpd = document.getElementById("rpd").value;
var totalMiles = document.getElementById("totalMile").value;
var totalDue = (rpm * totalMiles) + rpd;
document.getElementById("totalDue").innerHTML = totalDue;
}
</script>
<br>Total Amount Due: <input type="text" name="totalDue" id="totalDue"> <br>
</form>
<button id="showPaymentForm" onclick="totalDue()">Billing/Payment Info</button>
You need to set the value of the field instead of innerHTML in your case. Please refer to the fiddle here : https://jsfiddle.net/jhf18hsr/1/
I have put the parsing to integer values, which you can change to float as per your need, when reading the values from input controls.
function totalDue(){
var rpm = parseInt(document.getElementById("rpm").value) || 0;
var rpd = parseInt(document.getElementById("rpd").value) || 0;
var totalMiles = parseInt(document.getElementById("totalMile").value) || 0;
var totalDue = (rpm * totalMiles) + rpd;
document.getElementById("totalDue").value = totalDue;
}
First we put some values in both rpm and rpd, like 3 and 40. For now let us do this:
Car Rate Per Mile: <input type="text" name="rpm" id="rpm" value="3"> <br>
Or you can simply remove the default values if desired:
Car Rate Per Mile: <input type="text" name="rpm" id="rpm"> <br>
Same for rpd. In the future you may want to load this values from a database or something, it would be awesome since you stated you are new to JS and maybe you will try php later but not the case today; in the meantime remove the "disabled" part and input your desired values each time.
Second, add a parseFloat in your math so js treat your rpm and rpd values as numbers not as text; parseFloat will allow you to use and display some decimals, in contrast to parseInt.
var totalDue = (parseFloat(rpm) * parseFloat(totalMiles)) + parseFloat(rpd);
Third, change document.getElementById("totalDue").innerHTML = totalDue; for document.getElementById("totalDue").value=totalDue;. This way you will populate your output textbox onClick.
However this does not integrate dates into equation, you must ellaborate your JS function a little bit more to achieve this.
In your output textbox line I would add disabled since I don't want to write in this box, only show the result:
<br>Total Amount Due: <input type="text" name="totalDue" id="totalDue" disabled> <br>
Hope this helps.
<form>
Chapter 1 - Please enter how many copys you would like <br>
<input type="text" id="chap1"> <br><br>
Chapter 2 - Please enter how many copys you would like <br>
<input type="text" id="chap2"> <br><br>
Chapter 3 - Please enter how many copys you would like <br>
<input type="text" id="chap3"> <br><br>
Chapter 4 - Please enter how many copys you would like <br>
<input type="text" id="chap4"> <br><br>
Chapter 5 - Please enter how many copys you would like <br>
<input type="text" id="chap5"> <br><br>
<b> Total price : <output id = "total"> 0 </output> </b>
I'm trying to create a website in which you can order books by chapters, each chapter costs £2. I need it to multiply the value of the individual forms by 2 and then display this cost in the output. I would like to use java script in order to do this rather than jQuery.
I havent tried much as of yet as i cant find much on the subject, so any pointers in the right direction would be appreciated.
Thanks
function calc(){
price = 2;
fields = document.querySelectorAll("input[id^='chap']");
tot = 0;
for(i=0; i<fields.length; i++){
tot += fields[i].value * price;
}
document.getElementById("total").innerHTML = tot;
}
This is a simple example, you can improve it
fiddle link
<input type="text" id="chap1">
<input type="text" id="chap2">
<input type="text" id="chap3">
<input type="text" id="chap4">
<input type="text" id="chap5">
<b> Total price : <output id = "total"> 0 </output> </b>
<button onclick="myFunction()">Click me</button>
<script>
function myFunction() {
var text1= document.getElementById("chap1").value;
var text2= document.getElementById("chap2").value;
var text3= document.getElementById("chap3").value;
var text4= document.getElementById("chap4").value;
var text5= document.getElementById("chap5").value;
var total=parseInt(text1)+parseInt(text2)+parseInt(text3)+parseInt(text4)+parseInt(text5);
document.getElementById("total").innerHTML = total*2.1;
}
</script>
I have a form with four number inputs: hourly wage, hours worked, number of weeks, and salary.
I want to automatically fill-in the salary box based on the inputs from wage, hours, and weeks boxes.
So in theory, if hourly wage = 15, hours worked = 40, and number of weeks = 52 then the salary form box should automatically be set to "31200"
Any simple way to do this with javascript? I have tried a few different methods and can't seem to get it to work.
If it helps, I have already set all the form boxes to variables:
var wageBox = document.forms[0].wage;
var hoursBox = document.forms[0].hours;
var weeksBox = document.forms[0].weeks;
var salaryBox = document.forms[0].salary;
Edit: sorry, here's the HTML form code:
<fieldset id="incomeinfo">
<label for="wage">
Hourly wage:
<input type="number" id="wage" name="wage" placeholder="e.g. 15.00">
</label>
<label for="Hours">
Hours worked each week:
<input type="number" id="hours" name="hours" value="40" placeholder="e.g. 40">
</label>
<label for="Weeks">
Number of weeks a year:
<input type="number" id="weeks" name="weeks" value="52" placeholder="e.g. 52">
</label>
<br />
<br />
<label for="salary">
Salary:
<input type="number" id="salary" name="salary" placeholder="e.g. 31200" required>
</label>
</fieldset>
You can add a event for when the inputs change and calculate the salary based off of their values. Quick mock up.
Fiddle: http://jsfiddle.net/AtheistP3ace/6uatoyd2/
JS:
function calculateSalary () {
// Get all values we need to calculate
var wage = parseInt(document.getElementById('wage').value, 10);
var hours = parseInt(document.getElementById('hours').value, 10);
var weeks = parseInt(document.getElementById('weeks').value, 10);
// Calculate salary
var salary = wage * hours * weeks;
// Only update salary if we got number
if (!isNaN(salary)) {
document.getElementById('salary').value = salary;
}
}
// Get all inputs, loop and attach change event with calculateSalary handler
var inputs = document.getElementsByTagName('input');
var index = 0, length = inputs.length
for ( ; index < length; index++) {
inputs[index].addEventListener('change', calculateSalary);
}
HTML:
<input type="text" id="wage" placeholder="wage" />
<input type="text" id="hours" placeholder="hours" />
<input type="text" id="weeks" placeholder="weeks" />
<input type="text" id="salary" placeholder="salary" />
EDIT: Updated fiddle using your HTML. Same code works.
http://jsfiddle.net/AtheistP3ace/6uatoyd2/1/
This is the problem that I need to resolve.
Create a basic webpage that includes an input form. JavaScript is to be embedded into your HTML document.
The input form should include:
Field for user name input
Field for order quantity input
Read only field for item price – set to a value of 5.31
Read only field for order total cost
“submit button” that does NOT use any type of form button element
User should be able to input their name and order quantity, then click “submit”. When “submit” is clicked, form will calculate an order total, including sales tax of 8.25%. Once calculated, the order total form field is to be updated with a total, including dollar sign and two decimal places. An alert box should also be triggered stating the users name and a message indicating the order total including sales tax.
Be SURE to test with your own sample data to verity your calculations are correct.
I did the html and javascript but I can't calculate the const TAXRATE OF 8.25. The Item cost 5.31 and when the tax is included in the total, is huge amount calculated. Thanks for your help in advance. Please check my script here:
<link rel="stylesheet" type="text/css" href="2Examp.css">
<script type="text/javascript">
function calcOrder() {
const TAXRATE = 8.25;
var userName = document.getElementById("username").value;
var quantity = document.getElementById("quantity").value;
var cost = document.getElementById("cost").value;
var extendedCost = quantity * cost;
var taxAmount = extendedCost * TAXRATE;
var orderCost = extendedCost + taxAmount;
document.getElementById("costExtended").value = "$" + orderCost.toFixed(2);
alert("Hello " + userName + " - Your order of " + quantity + " widgets, total $" + orderCost.toFixed(2) + ", including tax.");
}
</script>
</head>
<body>
<h1>Lesson #2 - Sample Page</h1>
<form action="" method="post" enctype="multipart/form-data" name="wigetCalc">
<label for="form-name">Name</label>
<input name="username" id="username" type="text" maxlength="15" /><br />
<label for="form-quantity">Widget order quantity</label>
<input name="quantity" id="quantity" type="text" value="0" maxlength="3" /><br />
<label for="cost">Widget cost</label>
<input name="cost" id="cost" type="text" value="5.31" readonly="readonly" /><br />
<label for="order-total">Order Total</label>
<input name="costExtended" id="costExtended" type="text" readonly="readonly" /><br />
<p onclick="calcOrder();" >Process Order</p>
</form>
</body>
</html>
I believe the issue is that you are multiplying by 8.25 rather than 0.0825.
You could change
const TAXRATE = 8.25;
to
const TAXRATE = 0.0825;
Or do the following:
var taxAmount = extendedCost * (TAXRATE / 100);
I believe the problem is that you have a tax rate of 825%.
Instead of setting TAXRATE to 8.25, set it to 0.0825.
8.25% = 8.25 / 100 = 0.0825