I have the following function which I would like to simplify with a for loop maybe but don't know how to do it. any help will be much appreciated. Basically, if the field value is 0 or null then my total value (field) should be 0 otherwise if the field value is from 1 until 1000 then the total value becomes 5000. For every 1000 (i.e. 1001 until 2000) my total value should increase by 50 i.e. 5050. This should continue until the field value reaches 200000 and the total is 50000.
function calc56() {
var56 = parseFloat(document.getElementById('units56').value - 0);
if (var56 == '' || var56 == 0) {
document.getElementById('amount56').value = 0;
}
else if (var56 < 1000) {
document.getElementById('amount56').value = 5000;
}
else if ((var56 > 1000) && (var56 <= 2000)) {
document.getElementById('amount56').value = 5050;
}
else if ((var56 > 2000) && (var56 <= 3000)) {
document.getElementById('amount56').value = 5100;
}
}
Thanks in advance.
-
5I'm voting to close this question as off-topic because it is asking for an improve ment to working code. ask on codereview.stackexchange.comDaniel A. White– Daniel A. White2016年01月21日 11:07:21 +00:00Commented Jan 21, 2016 at 11:07
-
ˆ- migrate the question to the correct site, please.Stephan Bijzitter– Stephan Bijzitter2016年01月21日 11:12:48 +00:00Commented Jan 21, 2016 at 11:12
-
Few things about your code. If var56 is less than 0 you will still get 1000 and you say 1 to 1000 but your condition is var56 < 1000 which means it will only work to 999 and 1000 will not trigger any of the conditions.gothical– gothical2016年01月21日 11:19:30 +00:00Commented Jan 21, 2016 at 11:19
-
The below zero is a good pointStephan Bijzitter– Stephan Bijzitter2016年01月21日 11:20:38 +00:00Commented Jan 21, 2016 at 11:20
1 Answer 1
function calc56() {
var el = document.getElementById('units56'); //reference the dom element
var val = +el.value; //convert to float
if (!val) { //if no value, leave untouched
} else if (val < 0) { //if value is less than 0, make it 0.
el.value = 0;
} else { //otherwise, calculate new value
var mod = Math.floor(val / 1000); //calc how many 1000s fit in the value
el.value = mod * 50 + 5000; //use at least 5000, and add 50 for every 1000
}
}
I would suggest you also change the name of the function, as it's not very useful. However, this code right here should be the most efficient you can get while still keeping it readable.
If you need more clarification, feel free to ask in a comment!