jQuery - If Else statement not working but works if separated into individual if statements -
the code below works if statement
, subsequent else if statements
not fire. if separate 3 individual if statements
works fine. how can make them play nice together?
not working
if ( headinglength < 1 ) { // show error message $('.compose-wrap .message-heading .help-block').fadein(); } else if ( messagelength < 1 ) { // show error message $('.compose-wrap .message-body .help-block').fadein(); } else if ( formtaglength < 1 ) { // show error message $('.compose-wrap .choose-recipients .help-block').fadein(); }
working
if ( headinglength < 1 ) { // show error message $('.compose-wrap .message-heading .help-block').fadein(); } if ( messagelength < 1 ) { // show error message $('.compose-wrap .message-body .help-block').fadein(); } if ( formtaglength < 1 ) { // show error message $('.compose-wrap .choose-recipients .help-block').fadein(); }
it sounds if running else if
when dont want to. if 1 of former conditions solved condition exits, expected behaviour.
answer: if have on bottom thats not running expect running, don't want part inside else if. if need in else if need check logic comparison operators. e.g. >
>=
===
==
!=
<=
<
&&
etc.. switch them around until have want.
you can 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 1 of above yet, rinse , repeat...'); }
also, best end final else also, maybe console log, until dialed in.