Clinton Green Clinton Green - 6 months ago 25
jQuery Question

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

The code below only works for the

if statement
, the subsequent
else if statements
do not fire. But if I separate all 3 into individual
if statements
everything works fine. How can I make them all 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();
}

Answer

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 cpmparison 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();
  }

  if ( messageLength < 1 && headingLength >=1 ) {
Comments