[Solved] jQuery – If Else statement not working but works if separated into individual if statements


It sounds as if your running your else if when you dont want to. If any one of the former conditions are solved the condition exits, this is expected behaviour.

Answer:
If you have something on the bottom thats not running which you expect to be running, then you probably don’t want that part inside an else if. If you do need it in the else if you need to carefully check your logic comparison operators. e.g. the > >= === == != <= < && etc.. switch them around until you have what you want.

You can also combine them, e.g.

if ( headingLength < 1 ) {
    // show error message
    $('.compose-wrap .message-heading .help-block').fadeIn();
} else if ( (messageLength < 1) && headingLength >=1 ) {
    // show error message
    $('.compose-wrap .message-body .help-block').fadeIn();
} else {
    console.log('wasnt one of the above yet, rinse and repeat...');
}

Also, its best to end with a final else also, maybe with a console log, until you get it dialed in.

solved jQuery – If Else statement not working but works if separated into individual if statements