Javascript Update Total Sum from Fields - javascript

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

Related

button Function onclick not display in text filed

I'm writing a code that display content in text field on button submit click, but the code below is not working
<script>
function myFunction() {
var x = document.getElementById("cost").value;
if (document.getElementById("cost").value;) {
var netprofit = x-(16/100*x);
document.getElementById("net").value = +netprofit;
else if (document.getElementById("cost").value;) {
var commission = netprofit * 35/100;
document.getElementById("comm").value = +commission;
}
}
}
</script>
<form action="" method="POST">
<input type="text" id="cost" placeholder="kindly enter the cost value of project"><br><br>
<input type="text" name="" id="net" readonly="readonly"><br><br>
<input type="text" name="" id="comm" readonly="readonly"><br><br>
<input type="submit" value="Calculate" onclick="myFunction()">
</form>
I expect result to display in an input text onClicking button
As Harpel pointed out, you have to prevent the form from submitting. This is default behavior for forms that contain a input of type submit. I'd also suggest reorganizing your code a bit (vars for each input you selecting, etc). Something like the below:
<script>
function myFunction(event) {
event.preventDefault();
var costInput = document.getElementById("cost");
var netInput = document.getElementById("net");
var commInput = document.getElementById("comm");
if (costInput.value) {
var netprofit = costInput.value - (16/100 * costInput.value);
netInput.value = netprofit;
} else if (costInput.value) {
var commission = netprofit * 35/100;
commInput.value = commission;
}
}
</script>
<form action="" method="POST">
<input type="text" id="cost" placeholder="kindly enter the cost value of project"><br><br>
<input type="text" name="" id="net" readonly="readonly"><br><br>
<input type="text" name="" id="comm" readonly="readonly"><br><br>
<input type="submit" value="Calculate" onclick="myFunction(event)">
</form>
One additional thing; I'm not sure what the if statement is supposed to be checking, as it seems to be checking the same condition. If that's the case, you can just place both calculations for the input values into one if check like:
if (costInput.value) {
var netprofit = costInput.value - (16/100 * costInput.value);
netInput.value = netprofit;
var commission = netprofit * 35/100;
commInput.value = commission;
}
Your input type is submit. So it will always submit form and reload the page. You can do in function like
"return false" from your function,
event.preventDefault() add in your function //it will avoid the default behavior (in your case submit form).
Or use button in your HTML in place of ("input" with type "submit").
Here is working snippet, but i don't know why you are writing same condition in "if" and "else if"
function myFunction(e) {
e.preventDefault();
var cost = document.getElementById("cost").value;
if (cost) {
cost = +cost;
var netprofit = cost - (16 / 100 * cost);
var commission = netprofit * 35 / 100;
document.getElementById("net").value = +netprofit;
document.getElementById("comm").value = +commission;
}
}
<form action="" method="POST">
<input type="text" id="cost" placeholder="kindly enter the cost value of project"><br><br>
<input type="text" name="" id="net" readonly="readonly"><br><br>
<input type="text" name="" id="comm" readonly="readonly"><br><br>
<input type="submit" value="Calculate" onclick='myFunction(event)'>
</form>
<form action="" method="POST">
<input type="text" id="cost" placeholder="kindly enter the cost value of project"><br><br>
<input type="text" name="" id="net" readonly="readonly"><br><br>
<input type="text" name="" id="comm" readonly="readonly"><br><br>
<input type="button" value="Calculate" onclick="myFunction()">
</form>
<script>
function myFunction() {
var x = document.getElementById("cost").value;
if (document.getElementById("cost").value) {
var netprofit = x - (16 / 100 * x);
document.getElementById("net").value = +netprofit;
}
else if (document.getElementById("cost").value) {
var commission = netprofit * 35 / 100;
document.getElementById("comm").value = +commission;
}
}
</script>
Output

How do I use javascript or jquery to find a sum and product of values from a forms field inputs?

How do I use javascript or jquery to find a sum and product of number values that users enter into my forms fields. Thanks for your time and help.
Input 1 Value + Input 2 Value = Input A
Input A Value * .08 = Input B Value
Input A Value + Input B Value = Total Input
<form>
<input type="text" id="1" name="1">
<input type="hidden" id="2" name="2" value="33">
<input type="text" id="A" name="A">
<input type="text" id="B" name="B">
<input type="text" id="total" name="total">
<button type="button" id="button" name="button">
</form>
WHAT IVE TRIED
<script>
var $form = $('#contactForm'),
$summands = $form.find('.sum1'),
$sumDisplay = $('#itmttl');
$form.delegate('.sum1', 'change', function ()
{
var sum = 0;
$summands.each(function ()
{
var value = Number($(this).val());
if (!isNaN(value)) sum += value;
});
$sumDisplay.val(sum);
});
</script>
<script>
function multiply(one, two) {
if(one && two){
this.form.elements.tax.value = one * two;
} else {
this.style.color='blue';
}
}
</script>
Please find Fiddle link
JSFiddle
$(document).ready(function(){
$('#calculate').on('click',function(){
var v1 = $('#1').val(); // take first text box value
var v2 = $('#2').val(); // take second hidden text box value
$('#A').val(parseInt(v1)+parseInt(v2)); // set value of A
var aval = (parseInt($('#A').val()) * parseFloat(.8)); // calculate value of b
$('#B').val(aval);// set value of B
var totalval = parseInt($('#A').val()) + parseFloat(aval);
//calculate value for total
$("#total").val(totalval); // set total
})
});
I assume you want to update the fields when you lick the button? Created a snippet instead of a fiddle:
$("#button").click(function() {
$("#A").val( parseInt($("#1").val()) + parseInt($("#2").val()) );
$("#B").val(parseInt($("#A").val()) * .8);
$("#total").val( parseInt($("#A").val()) + parseInt($("#B").val()) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="1" name="1">
<input type="hidden" id="2" name="2" value="33">
<input type="text" id="A" name="A">
<input type="text" id="B" name="B">
<input type="text" id="total" name="total">
<button type="button" id="button" name="button">
</form>

How to get sum of input values?

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

My JQuery script is not retrieving form text values

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);
});

javascript sum calculation not functioning

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

Categories

Resources