I have a cgi form for employees to enter travel expenses. I'm using javascript to automatically display & send calculated data. The first (mileage) calculation on the form works. I cannot get the 2nd (total) calculation to appear. The result I am looking for is-
Miles * Rate (0.555) = Mileage (works)
MileageExp + other input fields = TotalExpenses (not working)
Here is the javascript-
<script type="text/javascript">
function totalexpense()
{
//mileage
a = document.event.Miles.value
b = document.event.Rate.value
c = a * b
z = c
document.event.Mileage.value = c.toFixed(2)
//total
d = document.event.Parking.value
e = document.event.Tolls.value
f = document.event.Plane.value
g = document.event.Train.value
h = document.event.Bus_Taxi.value
i = document.event.Lodging.value
j = document.event.Food.value
k = document.event.Other.value
l = z + d + e + f + g + h + i + j + k
document.event.Total_Expenses.value = l.toFixed(2)
}
</script>
The browser says there is an error in the document.event.Total_Expenses.value = l.toFixed(2) line.
HTML-
<p align="left" class="bold"><span class="style8">Mileage:</span><br>
Miles:
<input name="Miles" size="10">
X rate:
<input name="Rate" size="10" value="0.555" onblur="totalexpense();">
=
<input name="Mileage" size="10" readonly=true>
</p>
<p align="left">Parking:</span><br>
<input name="Parking" size="10" onblur="totalexpense();">
</p>
<p align="left">Tolls:</span><br>
<input name="Tolls" size="10" onblur="totalexpense();">
</p>
<p align="left">Airline Tickets:</span><br>
<input name="Plane" size="10" onblur="totalexpense();">
</p>
<p align="left">Train:</span><br>
<input name="Train" size="10" onblur="totalexpense();" >
</p>
<p align="left">Bus/Taxi:</span><br>
<input name="Bus_Taxi" size="10" onblur="totalexpense();" >
</p>
<p align="left">Lodging:</span><br>
<input name="Lodging" size="10" onblur="totalexpense();" >
Accomodations with- <input name="Accomodations_With" type="text" size="40" />
</p>
<p align="left" class="bold"><span class="style8">Food/Beverage:</span><br>
<input name="Food" size="10" onblur="totalexpense();" >
</p>
<p align="left">Other Expenses:</span><br>
<input name="Other" size="10" onblur="totalexpense();" >
</p>
<p align="left" class="bold"><span class="style8">Other Expense Notes:</span><br>
<span class="main style22">
<textarea name="Other_Expense_Notes" cols="50" rows="3" class="fieldbkgrd"></textarea>
</span>
</p>
<h3>Total Expenses:<br>
<input name="Total_Expenses" size="10" READONLY>
You need to convert the values from strings to numbers - .toFixed only works on a number.
document.event.Total_Expenses.value = Number(l).toFixed(2);
The reason your code worked with the mileage is because the 0.555 was cast to an integer in:
c = a * b; (c = # * 0.555)
You then do the "addition" which was treated like a concatenation:
z + d + e + f + g + h + i + j + k;
This converted the int to a string. Thus:
document.event.Total_Expenses.value = l.toFixed(2);
failed because the type cast was now a string.
If you want to convert a value explicitly then you need to use parseInt();
d = parseInt(document.event.Parking.value);
You need to convert the values from strings to numbers - .toFixed only works on a number.
document.event.Total_Expenses.value = Number(l).toFixed(2);
<input name="Total_Expenses" size="10" READONLY>
you set it as read only so you cannot set a value to read only elements, that's my best guess
Related
I have been asked to write a code in javascript to show the results in the output boxes based on the input data, the form should like the one shown in the attached image:Interest Calculator
Till now, I have written down the following code; however I am unable to get the results in the output boxes. Could someone please help. Thanks in advance.
function calc() {
{
var p = document.getElementById("p").value;
var r = document.getElementById("r").value;
var t = document.getElementById("t").value;
var int = f.int.value;
}
if (int === "si") {
var sip = (p * r * t) / 100
var ta = p + sip
document.getElementById("i").innerHTML = sip;
document.getElementById("a").innerHTML = ta;
} else {
var cta = p * (Math.pow((1 + r / 100), t))
var cmp = cta - p
document.getElementById("i").innerHTML = cmp;
document.getElementById("a").innerHTML = cta;
}
}
<form name="f">
<h1> Interest Calculator </h1>
Principal = <input type="text" id="p" autofocus>
<br><br><br> Rate of Interest = <input type="text" id="r">
<br><br><br> Time (in years) = <input type="text" id="t">
<br><br>
<h1> Interest Type </h1>
<input type="radio" name="int" id="int" value="si"> Simple Interest
<input type="radio" name="int" id="int" value="ci"> Compound Interest
<br><br>
<hr noshade> Interest <input type="text" id="i">
<br><br> Amount <input type="text" id="a">
<br><br>
<input type="button" name="cal" value="Calculate" onclick="calc()">
<input type="reset" value="Reset">
</form>
innerHTML is used to retrieve or update the content/markup inside a DOM node that can have children. For input elements, you have to use value to get or set the value of the field.
function calc() {
{
var p = document.getElementById("p").value;
var r = document.getElementById("r").value;
var t = document.getElementById("t").value;
var int = f.int.value;
}
if (int === "si") {
console.log("simple interest");
var sip = (p * r * t) / 100
var ta = p + sip
document.getElementById("i").value = sip;
document.getElementById("a").value = ta;
} else {
console.log("compound interest");
var cta = p * (Math.pow((1 + r / 100), t))
var cmp = cta - p
document.getElementById("i").value = cmp;
document.getElementById("a").value = cta;
}
}
<form name="f">
<h1> Interest Calculator </h1>
Principal = <input type="text" id="p" autofocus>
<br><br><br> Rate of Interest = <input type="text" id="r">
<br><br><br> Time (in years) = <input type="text" id="t">
<br><br>
<h1> Interest Type </h1>
<input type="radio" name="int" id="int" value="si"> Simple Interest
<input type="radio" name="int" id="int" value="ci"> Compound Interest
<br><br>
<hr noshade> Interest <input type="text" id="i">
<br><br> Amount <input type="text" id="a">
<br><br>
<input type="button" name="cal" value="Calculate" onclick="calc()">
<input type="reset" value="Reset"><br><br><br>
</form>
Replace innerHTML with value. Because input values are updated using value attribute. Also
the braces here
{
var p = document.getElementById("p").value;
var r = document.getElementById("r").value;
var t = document.getElementById("t").value;
var int = f.int.value;
}
is not required.
function calc() {
var p = document.getElementById("p").value;
var r = document.getElementById("r").value;
var t = document.getElementById("t").value;
var int = f.int.value;
if (int === "si") {
var sip = (p * r * t) / 100
var ta = p + sip
document.getElementById("i").value = sip;
document.getElementById("a").value = ta;
} else {
var cta = p * (Math.pow((1 + r / 100), t))
var cmp = cta - p
document.getElementById("i").value = cmp;
document.getElementById("a").value = cta;
}
}
<form name="f">
<h1> Interest Calculator </h1>
Principal = <input type="text" id="p" autofocus>
<br><br><br> Rate of Interest = <input type="text" id="r">
<br><br><br> Time (in years) = <input type="text" id="t">
<br><br>
<h1> Interest Type </h1>
<input type="radio" name="int" id="int" value="si"> Simple Interest
<input type="radio" name="int" id="int" value="ci"> Compound Interest
<br><br>
<hr noshade> Interest <input type="text" id="i">
<br><br> Amount <input type="text" id="a">
<br><br>
<input type="button" name="cal" value="Calculate" onclick="calc()">
<input type="reset" value="Reset">
</form>
Updated code. calculate() still not working. The monthly payment amount is ultimately not being passed to the "total" id box. Does anyone see what the underlying problem is here? My syntax seems to be correct, I believe there may be a problem with my specification of where each variable is applied in the code.
I am having problems getting the function calculate() to pass the correct result in "total." Any possible solutions? The action of clicking the calculate button should display the total, but is displaying nothing at all, as if the button does not activate the calculate function at all.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function calculate() {
var P = document.getElementById("price").value;
var D = document.getElementById("DP").value;
var R = document.getElementById("R").value;
var N = document.getElementById("N").value;
var i = (R / 1200);
var n = (N * 12);
var m = ((P - D) * i * Math.pow(1 + i,n)) / (Math.pow(1 + i,n) - 1);
var result = document.getElementById('total');
result.value = m;}
</script>
</head>
<div align="center">
<hr>
<form name id="Main">
<input type="number" id="price" placeholder="Price of the Car"/>
<br>
<br>
<input type="number" id="DP" placeholder="Down Payment"/>
<br>
<br>
<input type="number" id="R" placeholder="Annual % Rate"/>
<br>
<br>
<input type="number" id="N" placeholder="# of Years Loaned"/>
<br>
<br>
<input type="button" id="calculate" value="Calculate" onclick="javascript:calculate();"/>
<br>
<br>
<input type="number" id="total" placeholder="Total Cost..." readonly=""/>
<br>
<br>
<input type="reset" value="Reset">
</form>
<hr>
</div>
</html>
Use Math.pow() function instead. The ^ operator is not for mathematical power operations (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_XOR and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/pow).
Also, It's result.value = m, not the other way around :)
Also 2: R and M seem undefined to me, you have to initialize those variables with something, like you did with P and D.
Also 3: use chrome dev tools or anything like that. It will make your life much easier. Remember, javascript doesn't mean "no IDE" :D
Unfortunately, your original code will never work, as it has too many errors.
Here is the corrected fiddle for you, please, have a look:
http://jsfiddle.net/q330fqw8/
function calculate() {
var P = document.getElementById("price").value;
var D = document.getElementById("DP").value;
var R = document.getElementById("R").value;
var N = document.getElementById("N").value;
var i = (R / 1200);
var n = (N * 12);
var m = ((P - D) * i * Math.pow(1 + i,n)) / (Math.pow(1 + i,n) - 1);
var result = document.getElementById('total');
result.value = m;
}
I removed id="calculate" in HTML, because of this: Why JS function name conflicts with element ID?
In Javascript, the 4 variables P,D,R,N should be set properly. Finally, this m.value = result; -> result.value = m;
but I guess, you've already corrected some errors in the question. I worked with your original code.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function calculate() {
var P = document.getElementById("price").value;
var D = document.getElementById("DP").value;
var R = document.getElementById("R").value;
var N = document.getElementById("N").value;
var i = (R / 1200);
var n = (N * 12);
var m = ((P - D) * i * Math.pow(1 + i,n)) / (Math.pow(1 + i,n) - 1);
var result = document.getElementById('total');
result.value = m;}
</script>
</head>
<div align="center">
<hr/>
<form id="Main">
<input type="number" id="price" placeholder="Price of the Car" />
<br />
<br/>
<input type="number" id="DP" placeholder="Down Payment" />
<br/>
<br/>
<input type="number" id="R" placeholder="Annual % Rate" />
<br/>
<br/>
<input type="number" id="N" placeholder="# of Years Loaned" />
<br/>
<br/>
<input type="button" value="Calculate Monthly Payment" onclick="calculate();" />
<br/>
<br/>
Total Monthly Payment:<input type="number" id="total" placeholder="Total Cost..." readonly="" />
<br/>
<br/>
<input type="reset" value="Reset" />
</form>
<hr/>
</div>
hello im trying to add input totals to a grand total when any input is changed. i keep getting NaN in the total box. here is my code
<div class="col-md-6">
<input type="text" placeholder="Description" class="form-control" id="d" name="description" />
</div>
<div class="col-md-1">
<input type="text" placeholder="price." class="form-control" id="q" name="itemprice"/>
</div>
<div class="col-md-1">
<input type="text" placeholder="price" class="form-control" id="itemprice" name="itemprice1"/>
</div>
<div class="col-md-2">
<input type="text" placeholder="price" class="form-control" id="itemprice" name="itemprice2" onchange="myFunction()"/>
<td>Subtotal</td>
<td class="total" id="tot" for="tot">
<input type="total" id="total">
<script type="text/javascript">
function myFunction()
{
var answer = document.getElementById('total');
var x = document.getElementsByName('itemprice');
var y = document.getElementsByName('itemprice1');
var z = document.getElementsByName('itemprice2');
var d = document.getElementsByName('itemprice3');
answer.value = x.value + y.value + z.value + d.value;
}
</script>
Use Id's (fix duplicate id, remove reference to itemprice3 as it doesn't exist in the HTML). Convert text values to numbers before adding.
<div class="col-md-6">
<input type="text" placeholder="Description" class="form-control" id="d" name="description" />
</div>
<div class="col-md-1">
<input type="text" placeholder="price." class="form-control" id="itemprice" name="itemprice"/>
</div>
<div class="col-md-1">
<input type="text" placeholder="price" class="form-control" id="itemprice1" name="itemprice1"/>
</div>
<div class="col-md-2">
<input type="text" placeholder="price" class="form-control" id="itemprice2" name="itemprice2" onchange="myFunction()"/>
<td>Subtotal</td>
<td class="total" id="tot" for="tot">
<input type="total" id="total">
<script type="text/javascript">
function myFunction()
{
var answer = document.getElementById('total');
var x = document.getElementById('itemprice');
var y = document.getElementById('itemprice1');
var z = document.getElementById('itemprice2');
//var d = document.getElementsById('itemprice3');
// parseFloat converts to values, otherwise you'll concatenate the strings.
answer.value = parseFloat( "0" + x.value ) + parseFloat("0" + y.value) + parseFloat("0" + z.value); // + d.value;
document.getElementsByName returns a nodelist (because multiple nodes can have the same name). (That's why the name contains Elements with an 's' as opposed to getElementById, which returns 1 element at most.
Such a list doesn't have a value. You would either get the value of each element, or if you know it will always be one, get the value of the first element:
var y = document.getElementsByName('itemprice1')[0].value
But note, you don't have any elements that have the name itemprice3, so document.getElementsByName('itemprice3') will return a nodelist with 0 items. The line above will fail in that case.
Also note, you have two elements with id itemprice, which is illegal.
When that works, you will need parseInt() to convert the values to integers.
answer.value = parseInt(x.value) + parseInt(y.value) + parseInt(z.value) + parseInt(d.value);
If the inputs can contain floating point values as well, use parseFloat instead of parseInt.
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
I'm trying to get the data from a form and use the values for a final result.
The problem is (at least what it looks like when I'm debugging) is no values are being retried and stored in the vars I've created.
Here's the form:
<form>
<p>
<label for="numDigits">Number of Digits: </label>
<input type="text" id="numDigits" name="numDigits" />
</p>
<p>
<label for="num1">First Number: </label>
<input type="text" id="num1" name="num1" />
</p>
<p>
<label for="num2">Second Number: </label>
<input type="text" id="num2" name="num2" />
</p>
<p>
<label for="num3">Third Number: </label>
<input type="text" id="num3" name="num3" />
</p>
<p>
<input type="button" name="calc" id="calc" value="Calculate" />
</p>
<p id="result">Result will be displayed here when the button is pressed.</p>
</form>
and the JQuery script
$("#calc").on('click', function(){
var a = Number($("#numDigits").val());
var x = Number($("#num1").val());
var y = Number($("#num2").val());
var z = Number($("#num3").val());
var total = a * 3 + x + ((a + x - y) % a) + ((a + z - y) % a);
$("#result").html("<p class='id'>" + total + "</p>");
});
Thanks in advance for the help!
Edit: I updated the code to the working version.
Its seems to work well: fiddle
But note that, if you want to manipulate the input as numbers, you should write
var a = Number($("#numDigits").val());
var x = Number($("#num1").val());
var y = Number($("#num2").val());
var z = Number($("#num3").val());
Replace the replaceWith() with html(). I have The DEMO working:
$("#calc").click(function(){
var a = $("#numDigits").val();
var x = $("#num1").val();
var y = $("#num2").val();
var z = $("#num3").val();
var total = a * 3 + x;
total += ((y - x) % a);
total += ((y - z) % a);
$("#result").html(total);
});
I have created the code using Javascript but I'm getting and error when I hit the calculate button.
the formula im using is this:
A + B + C + D x E% + F =
The error I'm receiving is:
{"error": "Please use POST request"}
The code im using is:
// define a function to perform our calculation.
function calculate() {
// retrieve the values from the amount and percentage fields
// and store them in variables.
var A = $('#A').val();
var B = $('#B').val();
var C = $('#C').val();
var D = $('#D').val();
var E = $('#E').val();
var F = $('#F').val();
// calculation
var total = A + B + C + D * (E / 100) + F;
$('#total').val(total.toFixed(2));
return false;
}
$('#calculator').submit(calculate);
<form id="calculator">
<p>Base:
<input id="A" value="0.00" />
</p>
<p>Rush:
<input id="B" value="0.00" />
</p>
<p>Added:
<input id="C" value="0.00" />
</p>
<p>Extra:
<input id="D" value="0.00" />
</p>
<p>Ship:
<input type ="hidden" id="E" value="5" />
</p>
<p>
<input id="F" value="0.00" />
</p>
<hr />
<p>Total:
<input id="total" disabled="disabled" />
</p>
<p>
<input type="submit" />
</p>
</form>
I have create a plugin to create calculation form called calx, you can download it here
just define data formula in the target element, and initialize calx
<form id="calculator">
<p>Base: <input type="text" id="A" value="0.00" /></p>
<p>Rush: <input type="text" id="B" value="0.00" /></p>
<p>Added: <input type="text" id="C" value="0.00" /></p>
<p>Extra: <input type="text" id="D" value="0.00" /></p>
<p>Ship: <input type ="hidden" id="E" value="5" /></p>
<p><input type="text" id="F" value="0.00" /></p>
<hr />
<p>Total: <input type="text" id="total" disabled="disabled" data-formula="$A + $B + $C + $D * ($E/100) + $F" /></p>
<p><input type="submit" id="calculate" /></p>
</form>
javascript section
$(document).ready(function(){
$('#calculator').calx({autocalculate:false});
$('#calculate').click(function(e){
e.preventDefault();
$('#calculator').calx('update');
});
});
You're getting an unhandled TypeError from the middle of calculate():
$('#total').val(total.toFixed(2));
// TypeError: Object 0.000.000.0000.00 has no method 'toFixed'
With it being thrown, return false; isn't evaluated and the <form> still submits as normal. And, {"error": "Please use POST request"} is JSFiddle's way of refusing to handle the request since it's sent with HTTP GET.
The error is because total, A, B, etc. aren't Numbers and + also concatenates:
var total = A + B + C + D * (E / 100) + F;
// total = "0.00" + "0.00" + ... + "0.00";
<input> values are always Strings, so you'll need to parse them in order to add Numbers rather than concat Strings:
var A = parseFloat($('#A').val());
var B = parseFloat($('#B').val());
var C = parseFloat($('#C').val());
var D = parseFloat($('#D').val());
var E = parseFloat($('#E').val());
var F = parseFloat($('#F').val());
http://jsfiddle.net/wKr3u/
And, while the differences are negligible in most cases, e.preventDefault() (as Jeff Mercado suggested) has one benefit over return false:
It can be used sooner in the event handler, allowing the default action to still be prevented despite an error.
function calculate(ev) {
ev.preventDefault();
// retrieve the values from the amount and percentage fields
// ...
}
assuming that you want it to just calculate the total without actually submitting, you need to stop the submit event from proceeding:
$('#calculator').on('submit', function(ev) {
ev.preventDefault();
calculate();
});
On your code total.toFixed(2) giving this error and by default javascript will take the value as string so You have to handle that to
Update
string to number just do like this
var total = A*1 + B*1 + C*1 + D * (E / 100) + F*1;
HERE IS THE SOLUTION