0

As you can see from this code:

function setBodyClasses() {
    var answer = $surveyAns.getAnswer('QUEST223');
    answer = 'oro';
    if(!surveyUtils.isNullOrWhiteSpace(answer)) {
        if (answer.toLowerCase().indexOf('oro')) {
            $scope.bodyClasses = 'vip_gold';
        }
        else if (answer.toLowerCase().indexOf('platino')) {
            $scope.bodyClasses = 'vip_platinum';
        }
        else {
            $scope.bodyClasses = '';
        }
    }
}

For some reason the if else statement is not working correctly, as you can see the answer value is oro and it should stop on the first if, but when its on the first if condition it compares the value and it moves forward assuming that is not the same value, and for some other reason it enters the second if condition even though the value is different. Any idea why this is happening?

2
  • 7
    we can't see from screenshot, add the code. Commented Aug 28, 2014 at 17:22
  • 2
    Please post your code as text, not as an image. Commented Aug 28, 2014 at 17:23

3 Answers 3

4

You are incorrectly checking if answer contains the string. .indexOf() will return you where in the string it is. It could be 0, that's the start of the string (it's like an array, where it's zero-indexed). It returns -1 if it's not found.

If you just do if(answer.toLowerCase().indexOf('oro')) it will be false, since 0 is "falsly".

You want to do: if(answer.toLowerCase().indexOf('oro') >= 0).

Are you sure you want to use indexOf() in the first place? This is checking if the string "contains" oro. Are you sure you don't just need: if(answer.toLowerCase() === 'oro')?

Sign up to request clarification or add additional context in comments.

1 Comment

I need to check if the string contains 'oro'. Thank you
2

indexOf is returning 0, and 0 is a falsy value so its not entering the condition. Should be:

.indexOf('oro') > -1

Same with the other conditions

Comments

1

You are using indexOf to find the existence of "oro" in your string. IndexOf, however, correctly returns a value of 0, which equates to false in JavaScript. I personally would use answer.indexOf('oro') !== -1.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.