1

I want to check if the value entered by the user matches one of the values in my array. The below code is what I've got so far. Except at the moment no matter what I enter it always says "incorrect". Can someone tell me why this is and provide a possible fix?

function checkarray() {
  var ID = document.getElementById('input2').value
  for (var i = 0; i < array.length; i++) {
    if (ID == array[i]) {
      ID = "correct"
    } else {
      ID = "incorrect"
    }
  }
  document.getElementById('message').innerHTML = ID;
}
Meer
  • 2,765
  • 2
  • 19
  • 28
Karl
  • 83
  • 1
  • 4
  • 9
  • 1
    use `array.indexOf(ID) != -1` to see if the value exists. Basically you need to break out of loop once the correct one has been found – gurvinder372 Apr 13 '17 at 05:16
  • you are changing the initial value you are checking for within the loop itself..if you want to use loop.. use another variable to set correct/incorrrect and then break when you find – Suraj Rao Apr 13 '17 at 05:17
  • 1
    [break](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break) loop if `correct` condition is met – Satpal Apr 13 '17 at 05:17
  • [**Please search before posting**](/search?q=%5Bjs%5D+search+array). More about searching [here](/help/searching). – T.J. Crowder Apr 13 '17 at 05:18

1 Answers1

3

Use indexOf() on your array to find the index of the item like the following:

var myArr = ['10','20','30','40','50']

function checkarray() {
  var ID = document.getElementById('input2').value;
  var i = myArr.indexOf(ID);
  if(i > -1){
    document.getElementById('message').value = 'Exist';
  }
  else{
    document.getElementById('message').value = 'Does not exist';
  }
}
<input type="text" id="input2" />
<input type="button" onclick="checkarray()" value="Check"/>
<input type="text" id="message" />

Though my preferred way is by using includes() and ternary operator like the following way:

var myArr = ['10','20','30','40','50']

function checkarray() {
  var ID = document.getElementById('input2').value;
  document.getElementById('message').value = myArr.includes(ID)? 'Exist' : 'Does not exist';
}
<input type="text" id="input2" />
<input type="button" onclick="checkarray()" value="Check"/>
<input type="text" id="message" />
Mamun
  • 66,969
  • 9
  • 47
  • 59