Having trouble getting javascript to calculate fields - javascript

I have tried a couple different ways and I feel like this one is the closest to working, however it is not working. I was hoping that someone could point out and explain what I am doing wrong. I think that parseFloat could be my issue, but I am not sure.
window.onload = function () {
var purchPrice = document.getElementById('purchPrice');
var warrMile = document.getElementById('warrMile');
var currentMile = document.getElementById('currentMile');
var purchMile = document.getElementById('purchMile');
var mileAdjPerct = 0;
var mileAdjEach = 0;
var mileAdjTotal = 0;
}
function warrUpdate() {
var warrPerct = (parseFloat(currentMile.value) - parseFloat(purchMile.value)) / parseFloat(warrMile.value);
var warrEach = parseFloat(purchPrice.value) * warrPerct;
var warrTotal = warrEach * 4;
parseFloat(document.getElementById('mileAdjPerct').value = warrPerct);
parseFloat(document.getElementById('mileAdjEach').value = warrEach);
parseFloat(document.getElementById('mileAdjTotal').value = warrTotal);
}
Here is a fiddle: http://jsfiddle.net/hmhxybLL/

There are many issues with your code, the main one is that the variables you want to manipulate are locally scoped in the onload callback function. You have to make the variables global, but that's a bad idea, so among the many things one can do to avoid global variables, one is to encapsulate all your code in a warranty object:
<fieldset id="milewarr" onSubmit="milewarr()">
<p>Purchase Price Per Tire: <input type="number" name="purchPrice" id="purchPrice" onChange="warranty.update();" /></p>
<p>Mileage Warranty: <input type="number" name="warrMile" id="warrMile" onChange="warranty.update();" /></p>
<p>Current Vehicle Mileage: <input type="number" name="currentMile" id="currentMile" onChange="warranty.update();" /></p>
<p>Mileage at Purchase: <input type="number" name="purchMile" id="purchMile" onChange="warranty.update();" /></p>
<br />
<p>Adjustment Percentage: <input type="number" id="mileAdjPerct" readonly /></p>
<p>Adjustment Amount Each Tire: <input type="number" id="mileAdjEach" readonly /></p>
<p>Adjustment Discount Total: <input type="number" id="mileAdjTotal" readonly /></p>
</fieldset>
JS:
var warranty = (function() {
var purchPrice, warrMile, currentMile, purchMile, mileAdjPerct, mileAdjEach, mileAdjTotal;
return {
init: function() {
purchPrice = document.getElementById('purchPrice');
warrMile = document.getElementById('warrMile');
currentMile = document.getElementById('currentMile');
purchMile = document.getElementById('purchMile');
mileAdjPerct = document.getElementById('mileAdjPerct');
mileAdjEach = document.getElementById('mileAdjEach');
mileAdjTotal = document.getElementById('mileAdjTotal');
},
update: function() {
var warrPerct = (currentMile.value - purchMile.value) / warrMile.value; // caution: you should check for a divide by 0 first
var warrEach = purchPrice.value * warrPerct;
var warrTotal = warrEach * 4;
mileAdjPerct.value = warrPerct;
mileAdjEach.value = warrEach;
mileAdjTotal.value = warrTotal;
}
};
})();
window.onload = warranty.init;
http://jsfiddle.net/sebnukem/hmhxybLL/10/

Related

How to use DOM referenced .value's in different scopes? (refactoring/scope issue)

Thanks for stopping by! I have a piece of working code here at JSFiddle
It's a basic sort of a calculator that takes 4 values, runs them through a function and spits out the result. It works as expected until I try to refactor the code. As soon as I try to refactor it at least like this, which gives me NaN or 0 whatever I do.
Here's the original code itself
<!DOCTYPE html>
<html>
<body>
See how rich you can get just flipping stuff
<input type="number" id="bp" placeholder="Buying price">
<input type="number" id="n" placeholder="Amount">
<input type="number" id="sp" placeholder="Selling price">
<input type="number" id="t" placeholder="Tax % (1 by def, 3 prem)">
<button id="button" onclick="profit()">Get rich!</button>
<input type="text" id="r" placeholder="Profit (unless ganked)">
<button id="button" onclick="resetOnClick()">More!</button><br>
<p>Thank HumbleOldMan later, go get rich now.</p>
var profit = function(){
var bp = document.getElementById("bp").value;
var n = document.getElementById("n").value;
var sp = document.getElementById("sp").value;
var t = document.getElementById("t").value;
var result = Math.floor((sp*n-(sp*n/100)*t)-bp*n)
console.log(result);
document.getElementById("r").value = result;
}
var resetOnClick = function(){
document.getElementById("t").value =
document.getElementById("sp").value =
document.getElementById("n").value =
document.getElementById("bp").value = "";
console.log("reset clicked");
}
// just couldn't use assigned variables for DOM references for a reason. Must be scope bs or I'm just a noob//
And here is what I tried doing
<script type="text/javascript">
var bp = Number(document.getElementById("bp").value);
var n = Number(document.getElementById("n").value);
var sp = Number(document.getElementById("sp").value);
var t = Number(document.getElementById("t").value);
var r = Number(document.getElementById("r").value);
var result;
var calcProfit = function(bp,n,sp,t,r){
var result = Math.floor((sp*n-(sp*n/100)*t)-bp*n)
console.log(Number(result));
r = Number(result);
}
var resetOnClick = function(){
document.getElementById("t").value =
document.getElementById("sp").value =
document.getElementById("n").value =
document.getElementById("bp").value = "";
console.log("reset clicked");
}
</script>
The question is common. What am I doing wrong? I definitely don't wont to settle for the fist version and get used to doing things just like that. Any assistance will be highly appreciated.
You've to get the value of input fields while after click, not on page load which will give value to NaN because initially all are empty. Get inside the calcProfit function so you'll get updated values.

javascript format numbers from 8403.361344537816 to 8.403

I have a javascript to calculate taxes and it works like this
The html form
<td><input type="text" class="input-180" name="pbruto" id="pbruto" value="0"/></td>
<td><input type="text" class="input-180" name="pneto" id="pneto" value="0"></td>
<td><input type="text" class="input-180" name="piva" id="piva" value="0"></td>
The javascript code
<script>
var taxPerc = 1.19;
document.getElementById("pbruto")
.onkeyup = function(){
document.getElementById("pneto")
.value = parseFloat(document.getElementById("pbruto")
.value) * (1.00 / taxPerc)
document.getElementById("piva")
.value = parseFloat(document.getElementById("pbruto")
.value) - parseFloat(document.getElementById("pneto").value)
}
</script>
The problem is that the results I get from calculations are displayed like this
8403.361344537816
I need to get rid of those .361344537816 and format the number to 8.403 only
Any way to do this?
EDIT
No solutions yet
Lets say var x is holding the value, try:
x = parseInt(x) / 1000
It's easier to control the code, if you'd use variables instead of DOM to store values. I've re-written your code, and toLocaleString() method seems to do exactly what you want:
var taxPerc = 1.19;
document.getElementById("pbruto").addEventListener('input', function () {
var valNeto, valPiva,
elNeto = document.getElementById("pneto"),
elBruto = document.getElementById("pbruto"),
elPiva = document.getElementById("piva"),
valBruto = +(elBruto.value);
valNeto = valBruto * (1 / taxPerc);
valPiva = valBruto - valNeto;
elNeto.value = Math.round(valNeto).toLocaleString('de-DE');
elPiva.value = Math.round(valPiva).toLocaleString('de-DE');
});
label {
display: block;
}
<label>Bruto: <input id="pbruto" /></label>
<label>Neto: <input id="pneto" /></label>
<label>Piva: <input id="piva" /></label>

create photo gallery with controlled time interval by user

I have read that lesson:
http://html.net/tutorials/javascript/lesson17.php
which contains an example:
http://html.net/tutorials/javascript/lesson17_ex1.html
but I need to create a photo gallery with possibility to choose time between photos by user, so I want to modified that line of code:
galleryStarter = setTimeout("startGallery()", 2000);
to be as user want, so I add:
<input type="text" name="name" id="name"><br>
<input type="button" id="btnSub" value="User gallery"/>
<input type="button" id="btnSub" value="User gallery"/>
also:
var btnStart = document.getElementById("btnStart");
var btnStop = document.getElementById("btnStop");
var btnSub = document.getElementById("btnSub");
btnStart.onclick = startGallery;
btnStop.onclick = stopGallery;
btnSub.onclick = userGallery;
and:
function userGallery()
{
curImage.src = preloadedImgs[counter].src;
counter ++;
if (counter == preloadedImgs.length)
{
counter = 0;
}
var c=document.getElementById("name").value;
galleryStarter = setTimeout("userGallery()", c);
window.alert(c);
isGalleryOn = true;
}
but id didn't work.. what is the reason?
It is because you didn't clear previous timer.
clearTimeout(galleryStarter);
isGalleryOn = false;
Inside function userGallery() will solved your issue.
Check Fiddle Here.

Clear or delete variable before declaring it again with javascript

I am VERY NEW to javascript and am messing around with some math. I currently have:
<input disabled="disabled" type="text" id="backer-prediction-answer" width="100" value="" />
<FORM>
<INPUT type="button" value="Apply" name="button1" onclick="apply()">
</FORM>
<script>
var backerPrediction1 = document.getElementById("backer-prediction-1").value;
var backerPrediction2 = document.getElementById("backer-prediction-2").value;
var backerPrediction3 = document.getElementById("backer-prediction-3").value;
var backerPrediction4 = document.getElementById("backer-prediction-4").value;
function apply(){
var backers = parseInt(backerPrediction1,10) + parseInt(backerPrediction2,10);
document.getElementById("backer-prediction-answer").value = (backers);
}
</script>
I would like to be able to hit apply and have it recalculate. Do I need to delete the variable before declaring it again? If so, how do I do that?
Move the variables backerPredictionX inside the function, so that they are evaluated everytime you apply()
<script>
function apply(){
var backerPrediction1 = document.getElementById("backer-prediction-1").value;
var backerPrediction2 = document.getElementById("backer-prediction-2").value;
var backers = parseInt(backerPrediction1,10) + parseInt(backerPrediction2,10);
document.getElementById("backer-prediction-answer").value = (backers);
}
</script>
With jquery (code not validated):
function apply(){
var backerPrediction1 = $("#backer-prediction-1").val();
var backerPrediction2 = $("#backer-prediction-2").val();
var backers = parseInt(backerPrediction1,10) + parseInt(backerPrediction2,10);
$("#backer-prediction-answer").val(backers);
}

trouble with a currency converter in javascript

Im having trouble with this javascript. here is a n example
window.onload = initPage;
var euro;
var convert;
function initPage()
{
document.getElementById("convertButton").onclick = calcAnswer();
document.getElementById("conversionType").onchange = calcAnswer();
}
function calcAnswer()
{
//alert(document.getElementById("conversionType").value);
var value1 = document.getElementById("amount").value;
var conversionType = document.getElementById("conversionType").value;
//alert(conversionType);
if(var value = document.getElementById("conversionType").value=="polish");
document.getElementById("answer").value=(value1-32)/9*5;
else
document.getElementById("answer").value=value1*9/5+32;
}
here is the html
<h1>Currency Converter</h1>
<form name="convert">
Choose which currency you would like to convert to the Euro:
<select id="conversionType">
<option value="polish">Polish Zloty</option>
<option value="ukraine">Ukraine Hryvnia</option>
</select>
</br>
</br>
<hr>
Amount:<input id="amount" type="text" />
<input id="convertButton" type="button" value="Convert->"/>
To:
<input id="answer" type="text" name="answer" readonly="readonly"/>
</form>
im using an old temperature converter and havent changed that part part but even that part is not working.
For starters, these two lines are wrong:
document.getElementById("convertButton").onclick = calcAnswer();
document.getElementById("conversionType").onchange = calcAnswer();
Change them to:
document.getElementById("convertButton").onclick = calcAnswer;
document.getElementById("conversionType").onchange = calcAnswer;
You want to assign a function reference to onclick and onchange, not actually call the function and assign the return value.
Then, fix the if statement in calcAnswer like this:
function calcAnswer()
{
var amount = document.getElementById("amount").value;
var conversionType = document.getElementById("conversionType").value;
var answerElement = document.getElementById("answer");
//alert(conversionType);
if(conversionType == "polish") {
answerElement.value = (amount-32)/9*5;
} else {
answerElement.value = amount*9/5+32;
}
}
Should be
document.getElementById("convertButton").onclick = calcAnswer;
document.getElementById("conversionType").onchange = calcAnswer;
(without the parens)
You just need to reference the function, not execute it.

Categories