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.
Related
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);
}
<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/
I am having an issue with a bit of code in a form. I am trying to get the value from the user (dollar amount) and parse it to an integer. Then I need to perform calculations to add 2.9% to it and also add .30 to the product.
It seems that the issue is in the parsing...because I am getting errors in the console saying $sendAmount.val is not a function [when I enter $sendAmount.val()]. Yet, if I submit $userAmount.val(), it returns the dollar amount the user submitted (in a string).
Keep in mind that $userAmount is what the user enters and
$sendAmount is what is sent to Paypal.
Any help with this would be most appreciated... I have been trying to get this to work and have been coming up empty. I don't have much experience with parseInt.
Here is my code:
var $sendAmount = $("#payAMT");
var $userAmount = $("#valInput");
//Update the Amount
function $convFee() {
$sendAmount = parseInt($userAmount) * 1.029 + 0.30;
};
$agree.keyup($convFee);
$agree.click($convFee);
<div id="paypalWrap">
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="new">
<input type="hidden" name="amount" id="payAMT" value="0.00">
<input type="hidden" name="currency_code" value="USD">
<p>
<label for="os0" type="hidden" name="on0" value="Name:">Name:</label>
<input type="text" name="os0" maxlength="30" id="name">
</p>
<p>
<label for="os1" type="hidden" name="on1" value="Invoice Number:">Invoice Number:
<br />
<i>(Reference must be correct to get credit applied to your account)</i>
</label>
<input type="text" name="os1" maxlength="50" id="invoice">
</p>
<p>
<label for="os2" type="hidden" name="on2" value="Amount:">Amount being paid:</label>
<input type="text" name="os2" id="valInput" maxlength="15" placeholder="ex: 10.00 (not $10.00)">
</p>
<p>
<input type="checkbox" name "agreeCheck" id="agreeCheck" />
<label for="agreeCheck" type="hidden" name="agreeStatement" id="agreeStatement">
I understand and accept that I will be charged a convenience fee ($0.30 + 2.9% of transaction).
</label>
</p>
<input id="send" type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_paynowCC_LG.gif" disabled="disabled" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
</form>
</div>
This line has the same problem twice:
$sendAmount = parseInt($userAmount) * 1.029 + 0.30;
Both of these variables are DOM elements, not numbers. You need to interact with them as items, specifically their value elements (which are strings that can be parsed to numbers).
You need to retrieve the value from the first, and set the value of the second, e.g.:
$sendAmount.val(parseInt($userAmount.val) * 1.029 + 0.30);
See http://api.jquery.com/val/
I'm attempting to build a simple web form that takes 3 number inputs and outputs one number based on this formula: (a*b*c)/271).
This is the code I have but nothing is displayed in the output.
Clearly I have almost no clue what I'm doing.
I appreciate all help:
<body>
<img id="logo"src="images/a&l.png" alt="A&L Cesspool"/>
<h1>Grease Trap Gallon Calculator<h2>
<form name=calculator">
<input label="length" type="number" id="a">
<input label="width" type="number" id="b">
<input label="height" type="number" id="c">
<input type=Button value=Calculate onClick="gallons();">
<input name="OUTPUT" id="output" SIZE="4" maxlength="6" >
</form>
<script language="JavaScript" type="text/javascript">
<!--
function gallons() {
var LENGTH = document.calculator.a.value;
var WIDTH = document.calculator.b.value;
var HEIGHT = document.calculator.c.value;
var Total =(LENGTH*WIDTH*HEIGHT)/271;
document.calculator.OUTPUT.value = Total;
}
// -->
</script>
document.forms.calculator. There's no such thing as document.calculator. Also, form elements need name attributes to refer to them in form context, not IDs.
In other news
You have unclosed quotes
You have irregular naming conventions (OUTPUT, a, Total)
You have irregular quotes policy (sometimes you have, sometimes you don't).
So basically
<form name="calculator">
<input label="length" type="number" name="a">
<input label="width" type="number" name="b">
<input label="height" type="number" name="c">
<input type=Button value=Calculate onClick="gallons();">
<input name="OUTPUT" id="output" SIZE="4" maxlength="6">
</form>
function gallons() {
var LENGTH = document.forms.calculator.a.value;
var WIDTH = document.forms.calculator.b.value;
var HEIGHT = document.forms.calculator.c.value;
var Total = (LENGTH * WIDTH * HEIGHT) / 271;
document.forms.calculator.OUTPUT.value = Total;
}
Please grab a proper tutorial from MDN or some similar good source, and start reading.
Your call to document.calculator is not finding the element because its looking by id
change your form definition and it will work
<form name="calculator" id="calculator">