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);
});
Related
I am working on creating a simple increase/decrease percentage calculator using HTML and JavaScript. I honestly am not sure where my actual code is going wrong. It worked fine until I added an if/then statement in the JavaScript. Everything "appears" to be right, but the result is not printing to the screen at the tag ID I specify. I am new to JavaScript and HTML so this is just some learning for me. Thanks in advance!
function getPercentageChange() {
var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
if (button1.checked){
var d_oldNumber = document.getElementById('originalnumber').value;
var d_newNumber = document.getElementById('newnumber').value;
var decreaseValue = d_oldNumber - d_newNumber;
var decreaseresults = (decreaseValue / oldNumber) * 100;
document.getElementById('percentageIncrease').innerHTML = descreaseresults + '%';
} else if (button2.checked) {
var i_oldNumber = document.getElementById('originalnumber').value;
var i_newNumber = document.getElementById('newnumber').value;
var increaseValue = i_oldNumber - i_newNumber;
var increaseresults = (increaseValue / i_oldNumber) * 100;
document.getElementById('percentage').innerHTML = increaseresults + '%';
}
}
Percentage Increase <input type="radio" name="radionbutton" value="1" id="button1"/><br>
Percentage Decrease <input type="radio" name="radionbutton" value="2" id="button2"/><br>
<p>Original Number:
<input type="numeric" id="originalnumber" value=""><br>
New Number:
<input type="numeric" id="newnumber" value=""><br><br>
</p>
<input type="button" value="Calculate" onclick="getPercentageChange();">
<div id = "percentage"></div>
<p id="percentage"></p>
This statement uses an undefined variable oldNumber. Perhaps change it to d_oldNumber?
var decreaseresults = (decreaseValue / oldNumber) * 100;
You simply had some miss-spelled variables: d_oldNumber, oldNumber and the id oldNumber.
function getPercentageChange() {
var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
if (button1.checked) {
var d_oldNumber = document.getElementById('originalnumber').value;
var d_newNumber = document.getElementById('newnumber').value;
var decreaseValue = d_oldNumber - d_newNumber;
var decreaseresults = (decreaseValue / d_oldNumber) * 100;
document.getElementById('percentage').innerHTML = decreaseresults + '%';
} else if (button2.checked) {
var i_oldNumber = document.getElementById('originalnumber').value;
var i_newNumber = document.getElementById('newnumber').value;
var increaseValue = i_oldNumber - i_newNumber;
var increaseresults = (increaseValue / i_oldNumber) * 100;
document.getElementById('percentage').innerHTML = increaseresults + '%';
}
}
Percentage Increase <input type="radio" name="radionbutton" value="1" id="button1" /><br> Percentage Decrease <input type="radio" name="radionbutton" value="2" id="button2" /><br>
<p>Original Number:
<input type="numeric" id="originalnumber" value=""><br> New Number:
<input type="numeric" id="newnumber" value=""><br><br>
</p>
<input type="button" value="Calculate" onclick="getPercentageChange();">
<div id="percentage"></div>
<p id="percentage"></p>
As a few of your variables equate to the same result, you could simplify this function to save yourself mix-ups. There are a few instances where there were mis-spellings of variable names in your code
function getPercentageChange() {
var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
var oldNumber = document.getElementById('originalnumber').value;
var newNumber = document.getElementById('newnumber').value;
var difference = oldNumber - newNumber;
var results = (difference / oldNumber) * 100;
if (button1.checked) {
document.getElementById('percentage').innerHTML = results + '%';
} else if (button2.checked) {
document.getElementById('percentage').innerHTML = results + '%';
}
}
Percentage Increase <input type="radio" name="radionbutton" value="1" id="button1" /><br> Percentage Decrease <input type="radio" name="radionbutton" value="2" id="button2" /><br>
<p>Original Number:
<input type="numeric" id="originalnumber" value=""><br> New Number:
<input type="numeric" id="newnumber" value=""><br><br>
</p>
<input type="button" value="Calculate" onclick="getPercentageChange();">
<div id="percentage"></div>
<p id="percentage"></p>
Hope this helps
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>
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
simple numerical code to compute the hypotenuse with the numeric value, i dont know how to decpiher the hypotenuse code in Javascript language" hypo = the square_root of ( sidea squared plus sideb squared)", when i go to my webpage it just shows up blank...what am i missing please inform me on what it was thanks
<html>
<head>
<title> Quadratic</title>
<script type="text/javascript">
function Calculate() {
var a = document.getElementById("aBox").value;
var b = document.getElementById("bBox").value;
var c = document.getElementById("cBox").value;
var x = document.getElementById("xBox").value;
var y = 0;
document.getElementById('outputDiv').innerHTML= 'result y = : 'y = ax2 + bx + c;">
}
</head>
<body>
<h2>Quadratic</h2>
<p>
a: <input type="text" id="aBox" value="2">
<br>
b: <input type="text" id="bBox" value="3">
<br>
c: <input type="text" id="cBox" value="4">
<br>
x: <input type="text" id="xBox" value="5">
<br>
result y = : <input type="text" id="yBox" value="0">
</p>
<div id="outputDiv">
<input type="button" value="Calculate quadratic" onclick="Calculate();">
</div>
<hr>
</script>
</body>
</html>
You need to close the script tag in the right place
}
</script>
</head>
<body>
then your page will at least display
then you need to fix this
.innerHTML= 'result y = : 'y = ax2 + bx + c;">
Try this fiddle. http://jsfiddle.net/harendra/CpBZu/
This fixes your calculate function to calculate hypotenuse of square. You can do same for other squares as well.
function Calculate() {
var a = parseInt(document.getElementById("aBox").value);
var b = parseInt(document.getElementById("bBox").value);
var c = parseInt(document.getElementById("cBox").value);
var x = parseInt(document.getElementById("xBox").value);
var y = Math.sqrt(a*a+a*a);
document.getElementById('yBox').value=y
//document.getElementById('outputDiv').innerHTML= 'result y = : 'y = ax2 + bx + c";
}
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