Skip to content

Why does my calculation function not run properly?

I need to create a BAC calculator in JavaScript. When I run the code, the form validation works but the calculate function doesn’t seem to run.

    function validateForm() {
    let weight = document.getElementById("weight").value;
    let beer = document.getElementById("beer").value;
    let wine = document.getElementById("wine").value;
    let liquor = document.getElementById("liquor").value;
    let hours = document.getElementById("hours").value;
    if (weight <= 0){
        alert("Weight must be more than zero")
        return false;
    }

    else if (beer<0 || wine<0 || liquor<0 || hours<0){
        alert("Number must be zero or higher")
        return false;
    }
    else if(isNaN(weight)||isNaN(beer)||isNaN(wine)||isNaN(liquor)||isNaN(hours)){
        alert("Answer must be a number")
        return false;
    }
    else if (weight == null||beer == null||wine == null||liquor == null||hours == null){
        alert("All fields must be filled")
        return false;
    }
    else{
        return calculate;
    }
}
function calculate() {
    let weight = document.getElementById("weight").value;
    let beer = document.getElementById("beer").value;
    let wine = document.getElementById("wine").value;
    let liquor = document.getElementById("liquor").value;
    let hours = document.getElementById("hours").value;
    let answer = (((((beer * 0.54)+(wine*0.6)+(liquor*0.6))*7.5)/weight)-(hours*0.015)).toFixed(3)
    document.getElementById("bac").value = answer;
    document.getElementById("answer").append(answer);
    return answer;
}

If anyone has any answers I’d be more than happy. Thank you.

Answer

In the validateForm()-method, try return calculate();