Salini
Salini

Reputation: 347

Comparing an input to the values of an array only works with a single value

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";
        }
    }
}

Upvotes: 0

Views: 96

Answers (1)

Jesse
Jesse

Reputation: 2830

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>

Upvotes: 5

Related Questions