fatsoua
fatsoua

Reputation: 11

JavaScript - simplify/shorten code

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.

Upvotes: 0

Views: 83

Answers (1)

Stephan Bijzitter
Stephan Bijzitter

Reputation: 4595

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!

Upvotes: 1

Related Questions