JavaScript math not adding up correctly - javascript

I am having a problem with my math function below. The depreciationFee variable adds up correctly, but for some odd reason the financeFee variable does not. I am trying to calculate the monthly lease payment of a vehicle. Whenever I submit the numbers for financeFee it shows two number appended to each other rather than added together. Is there a reason the numbers aren't adding up correctly?
$(".submit").click(function() {
function calculateLease() {
var capitalCost = $(".capital-cost").val();
var downPayment = $(".down-payment").val();
var residualCost = $(".residual-cost").val();
var monthTerm = $(".month-term").val();
var moneyFactor = $(".money-factor").val();
var depreciationFee = (((capitalCost - downPayment) - residualCost) / monthTerm);
// THIS IS THE ONE THAT DOESN'T WORK
var financeFee = ((capitalCost - downPayment) + residualCost);
alert(financeFee);
}
calculateLease();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="lease-calculator-container">
<h3>LEASE CALCULATOR</h3>
<form method="get">
<input type="text" class="capital-cost" placeholder="MSRP" />
<br />
<input type="text" class="down-payment" placeholder="DOWN PAYMENT" />
<br />
<input type="text" class="residual-cost" placeholder="RESIDUAL" />
<br />
<input type="text" class="month-term" placeholder="TERM IN MONTHS" />
<br />
<input type="text" class="money-factor" placeholder="MONEY FACTOR" />
<br />
</form>
<input type="submit" class="submit" value="CALCULATE" />
<div class="monthly-cost"></div>
<div class="total-cost"></div>
</div>

Do a parseInt(value,10) for intergers or parseFloat(value) for float.
JavaScript appends the values if the data type is not a number.

Related

Calculating with dynamic textboxes

I am working with dynamic textboxes. With this dynamic textboxes I want to perform a calculation:
The calculation is simple. I want to calculate the total value of the textboxes.
In my example I am using 3 textboxes with the ids:value1,value2andvalue3`.
The calculation I want to make is:
value1 + value2 + value3 = total
In my javascript I dont want to define all these values becouse the possible ids numbers are unlimited.
So my question is. How can I get the total count of the values without defining each ID.
Here is my script:
Items:<br />
<input type="text" name="value[]" id="value1" placeholder="Value 1" onChange="getPrice(this.value)" /> <br />
<input type="text" name="value[]" id="value2" placeholder="Value 2" onChange="getPrice(this.value)" /> <br />
<input type="text" name="value[]" id="value3" placeholder="Value 3" onChange="getPrice(this.value)"/> <br />
<br />
Total: <br />
<input type="text" name="total" id="total" placeholder="Total"/> <br />
<script>
function getPrice() {
var numVal1 = Number(document.getElementById("value").value);
var totalValue = numVal1;
document.getElementById("total").value = totalValue.toFixed(2);
}
</script>
Example: http://jsfiddle.net/8vhot05u/
You could go over all value[] inputs and sum them up:
let total = 0;
for(const el of document.getElementsByName("value[]"))
total += +el.value;
document.getElementById("total").value = total;

Multiple inputs update multiple textarea's

exactly what the title describes.
i'm wanting 1 set of 6/7 input fields to be able to update 4/5 different textareas for different templates to copy paste from with the input elements.
ive tried using getelementsbyclassname but it doesnt seem to work with multiple textareas.
a simple example for multiple inputs updating multiple textarea's would be enough to play with.
This is what i have so far, and its not complete.
1 name: <input type="text" name="1stTarget" onblur="tst1(this);" /><br />
2 name: <input type="text" name="2ndTarget" onblur="tst1(this);" /><br />
Email address: <input type="text" name="3rdTarget" onblur="tst1(this);" /><br />
Phone #: <input type="text" name="4thTarget" onblur="tst1(this);" /><br />
Schedule: <input type="text" name="5thTarget" onblur="tst1(this);" /><br />
<textarea name="result" id="result1" onClick="this.select();" class="disable">Hello 1stTarget, 2ndTarget i would like to confirm your email address 3rdTarget and phone # 4thTarget and the time you will be at work 5thTarget</textarea>
<br />
<textarea name="result2" id="result2" onClick="this.select();" class="disable">1stTarget and 2ndTarget updated their 5thTarget and their 4thTarget including their 3rdTarget</textarea><input type="reset" value="Reset!" />
using
<script type="text/javascript">
function tst1(elm){
var trgt=document.getElementById('result1');
trgt.value=trgt.value.replace(elm.getAttribute('name'), elm.value);
}
</script>
If I were you, I would not try to replace the text in the textarea but instead simply build the string you need from your inputs and set the text when that's done. Something like the below would work for that:
Note THe main function you need is jQuery's eq()
$('#fill').click(function(elm) {
var hasErrors=false;
var $updateElms=$('.update');
$updateElms.removeClass('hasError');
$updateElms.each( function(i,e){
if($(e).val()==''){
hasErrors=true;
$(e).addClass('hasError');
}
});
if(hasErrors) return;
var name1 = $updateElms.eq(0).val();
var name2 = $updateElms.eq(1).val();
var email = $updateElms.eq(2).val();
var phone = $updateElms.eq(3).val();
var schedule = $updateElms.eq(4).val();
var text0 = 'Hello '+name1+', '+name2+' I would like to confirm your email address '+email+' and phone # '+phone+' and the time you will be at work '+schedule;
var text1 = 'Hi '+name1+', '+name2+' we have recieved your confirmation that your email address is '+email+' and phone # is '+phone+' and that you will be at work '+schedule;
var text2 = 'Hello '+name1+', '+name2+' we have attempted to reach you via your email address '+email+' and phone # '+phone+' to advise that you missed your shift at '+schedule;
$('.result:eq(0)').val(text0);
$('.result:eq(1)').val(text1);
$('.result:eq(2)').val(text2);
});
.hasError{
color:red;
background-color:#F9B9B9;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
1 name:
<input type="text" class="update"/>
<br />
2 name:
<input type="text" class="update"/>
<br />
Email address:
<input type="text" class="update"/>
<br />
Phone #:
<input type="text" class="update"/>
<br />
Schedule:
<input type="text" class="update"/>
<br />
<input type="button" id="fill" value="Fill Textareas"/>
<br />
<textarea name="result" class="disable result"></textarea>
<br />
<br />
<textarea name="result" class="disable result"></textarea>
<br />
<br />
<textarea name="result" class="disable result"></textarea>
<br />
<input type="reset" value="Reset!" />using

calculate two input field values in javascript

Hi i want to calculate two input field values and result will show in third input field so i want to write code in ajax page
<input id="a1" type="text" />
<input id="a2" type="text" onblur="Calculate();" />
<input id="a3" type="text" name="total_amt" value="" />
here javascript function
<script>
function Calculate()
{
var resources = document.getElementById('a1').value;
var minutes = document.getElementById('a2').value;
document.getElementById('a3').value=parseInt(resources) * parseInt(minutes);
document.form1.submit();
}
</script>
starting its working but nw its not working please help me
Thanks in Advance
Look this! Work it.
http://jsfiddle.net/op1u4ht7/2/
<input id="a1" type="text" />
<input id="a2" type="text" onblur="calculate()" />
<input id="a3" type="text" name="total_amt" />
calculate = function()
{
var resources = document.getElementById('a1').value;
var minutes = document.getElementById('a2').value;
document.getElementById('a3').value = parseInt(resources)*parseInt(minutes);
}
Try AutoCalculator https://github.com/JavscriptLab/autocalculate Calculate Inputs value and Output By using selector expressions
Just add an attribute for your output input like data-ac="(#firstinput+#secondinput)"
No Need of any initialization just add data-ac attribute only. It will find out dynamically added elements automatically
FOr add 'Rs' with Output just add inside curly bracket data-ac="{Rs}(#firstinput+#secondinput)"
My code is from an answer above. Special thank for you!
calculate = function (a, p, t) {
var amount = document.getElementById(a).value;
var price = document.getElementById(p).value;
document.getElementById(t).value = parseInt(amount)*parseInt(price);}
<input type="number" id="a0" onblur="calculate('a0', 'p0', 't0')">
<input type="number" id="p0" onblur="calculate('a0', 'p0', 't0')">
<input type="number" id="t0" >
<hr>
<input type="number" id="a1" onblur="calculate('a1', 'p1', 't1')">
<input type="number" id="p1" onblur="calculate('a1', 'p1', 't1')">
<input type="number" id="t1" >
put in you form id="form1"
the JavaScript is look like this.
calculate = function()
{
var resources = document.getElementById('a1').value;
var minutes = document.getElementById('a2').value;
document.getElementById('a3').value = parseInt(resources)*parseInt(minutes);
document.form1.submit();
}

Access HTML form values in javascript

Here is what I am trying to achieve, but for some reason, it does not work:
Javascript:
<script type="text/javascript">
function calculate() {
var n1 = getElementById("1").value
var n2 = getElementById("2").value
var answer = n1+n2
alert(answer)
}
</script>
HTML:
<form id="form">
<input id="1" type="text" />
<input id="2" type="text" />
<input type="button onClick="calculate()" value="Go" />
</form>
I am not sure where I went wrong, Can someone help please?
You shouldn't start ID's with numbers - in HTML4 and CSS it isn't allowed, in HTML5 it is allowed, but it's not good practice to do so.
Also, in this context it is illegal in HTML5 - as an ID starting with a number requires at least one letter afterwards.
So, firstly replace the numbered ID's with letters/words.
Apart from this, you need to fix the syntax errors mentioned below:
Replace getElementById("id").value with document.getElementById("id").value;
and also replace <input type="button onClick="calculate()" value="Go" />
with <input type="button" onClick="calculate()" value="Go" /> (notice there was a closing " missing for "button").
Here is a working jsFiddle.
Here is the code used in the jsFiddle:
Javascript:
function calculate() {
var n1 = document.getElementById("aItem").value;
var n2 = document.getElementById("bItem").value;
var answer = n1+n2;
alert(answer);
}
HTML:
<form id="form">
<input id="aItem" type="text" />
<input id="bItem" type="text" />
<input type="button" onClick="calculate()" value="Go"/>
</form>
HTML:
<input id="val1" type="text" value="100" />
<input id="val2" type="text" value="200"/>
<input type="button" onclick="calculate()" value="Go" />
JavaScript:
function calculate() {
var n1 = +(document.getElementById("val1").value);
var n2 = +(document.getElementById("val2").value);
var answer = n1+n2;
alert(answer);
}
This will add the 2 numeric values entered rather than concatenating them.

HTML/Javascript: Trigger 2 different action from 1 button

How can we trigger 2 action from 1 button? How do we make a button/or links which can go/scroll to element "#result" and trigger the function "calculateThis" (proceed data from a form)
How do I mix the these into 1 button/link?
Submit
and
<button class="button" onclick="calculateThis(this.form); return false;">Submit</button>
// UPDATED
Here is the complete code
<script type="text/javascript">
function calculateThis(form) {
var userweight=parseInt(form.weight.value, 10);
var caffeineamount=parseInt(form.caffein.value, 10);
var caffeinetimes=parseInt(form.caffeintimes.value, 10);
var totalcaffeine=caffeineamount*caffeinetimes;
console.log(totalcaffeine)
// Calculate max caffeine per person
var maxcaffeine=userweight*10;
// Calculate remaining after 24 hours
// Half life = 6 hours
var totalcaffeineafter=totalcaffeine*(1/16);
// Calculating how many hours until the caffeine completely digested
var totaldigest=totalcaffeine;
var digesttime=0;
while (totaldigest>0.05) {
totaldigest=totaldigest*(1/2);
digesttime++;
}
digesttime=digesttime*6;
// Calculating when the user will probably die of overdose
var countcaffeine=0;
var overdosetime=1;
while (countcaffeine<maxcaffeine){
countcaffeine=countcaffeine+totalcaffeine;
overdosetime++;
}
// Show total amount of caffeine
document.getElementById("showtotalkafein").innerHTML=totalcaffeine;
// Show amount of caffeine after 1 day
document.getElementById("showtotalkafeinsetelah").innerHTML=totalcaffeineafter;
// Show digest time
document.getElementById("showwaktudigest").innerHTML=digesttime;
// Show overdose
document.getElementById("showberapakali").innerHTML=overdosetime;
return false;
}
</script>
<form class="form">
Weight<br />
<input type="text" name="weight" class="required" value="" /><p />
Amount of caffein in coffee<br />
<input type="text" name="caffein" class="required" value="" /><p />
How many times drinking coffeein a day<br />
<input type="text" name="caffeintimes" class="required" value="" /><p />
Submit
</form>
<br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br />
<h1 id="result">Result</h1>
<p id="showtotalkafein">Show Caffein Total Here</p>
<p id="showtotalkafeinsetelah">Show Caffeine Amount After 24 hours</p>
<p id="showwaktudigest">Show Digest Time Here</p>
<p id="showberapakali">Show Overdose Time Here</p>
You should be able to do the same as in the button, i.e
Submit
Doesn't this work?
JaggenSWE's answer is almost there, but don't return false since this suppresses default behaviour, which is to follow the link.
Submit
I wouldn't advise using inline event handlers though.
Edit
This works. http://jsbin.com/uwatab/3/
Its always preferable to attach an onsubmit handler to a form, rather than button onclick. This way, pressing enter in your form still executes your javascript.

Categories