0

I have some fruits names stored in an array. If the user enters a food name which is already stored in the array then true should be returned, otherwise false.

But it only returns true when I input the value Mango, otherwise always returning false, why?

Here's my code:

JSfiddle link

HTML:

<input type="text" id="value" />
<button onclick="check()">test</button>
<p id="pValue">
</p>

JavaScript:

var myVar;

check = function() {
    myVar = document.getElementById("value").value;

    var fruits = ['Banana', 'Orange', 'Apple', 'Mango'];

    for(i = 0; i < fruits.length; i++) {
        if(myVar == fruits[i]) {
            document.getElementById("pValue").innerHTML = "true";
        }
        else {
            document.getElementById("pValue").innerHTML = "false";
        }
    }
}

1 Answer 1

5

This is because you are using a for increment loop so only the last value will return true. You can add a break; to the loop if you choose to keep this as the method. See updated fiddle below ::

var myVar;


check = function() {
    myVar = document.getElementById("value").value;
    var fruits = ['Banana', 'Orange', 'Apple', 'Mango'];

    for (i = 0; i < fruits.length; i++) {
        if (myVar == fruits[i]) {
            document.getElementById("pValue").innerHTML = "true";
            break;
        } else {
            document.getElementById("pValue").innerHTML = "false";
        }
    }
}
<input type="text" id="value" />
<button onclick="check()">test</button>
<p id="pValue">
</p>

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

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.