+ 1
Problem in Javascript with else if and condition
6 Answers
+ 6
There are 2 mistakes in your actual code:
+ imc global variable is refering to the function imc() (that's the reason why the last else is always used)
+ imc variable computed in imc() function is private to this function... you need to use a global variable to be able to access it from the comment() function
Fixed code:
var IMC;
function imc(){
var t = parseFloat(document.getElementById("tall").value) ;
var w = parseFloat(document.getElementById("weight").value) ;
IMC = w / (t*t) ;
document.getElementById("result").innerHTML ="Result =" + IMC;
}
function comment() {
if (IMC <= 16.5) {
document.getElementById("comment").innerHTML = "you are light";
} else if (IMC <= 25) {
document.getElementById("comment").innerHTML = "not bad";
} else {
document.getElementById("comment").innerHTML = "you are too heavy"; }
}
+ 4
1. You're missing semicolons after each of your statements in the if, else-if, else blocks.
2. Try; else if (16.5 < imc && imc <= 25)
You can't chain your conditions (in JavaScript) the way you have them. Each condition can only have 1 operand on each side of a conditional operator.
+ 4
Yes, @ChaoticDawg is right: better practice would be to avoid use of global variables...
Anyway, in most of cases, that's not a problem (especially in simplest project, not using many linked JS files not written by yourself), and there's many way to avoid use of global variables, among wich best globaly practice would be to wrap all your codes in anonymous function to create a private pseudo-global scope, assigned to one of (on)'load' or 'DOMContentLoaded' events, and define/register from it the needed event listeners rather than using html event listener attributes ;)
+ 3
You also have a scope resolution problem. In the comment function imc is returning the imc function definition, not the value of imc within the imc function, which is what i'm guessing you want. You can fix this by adding a return imc; statement to the end of the imc function and then adding parentheses after each of the calls to imc in your comment functions if, else-if, else statements.
edit: what @visph will work also, but this will expose the IMC variable.
+ 2
Semicolons are optional in almost cases in JS, but not all cases. So, better practice is to put them systematically to avoid unexpected bugs ^^
0
Now It work š
thank guy