skip to Main Content

I am currently learning JavaScript Arrays and am trying to do a small program that allows a user to enter a value input. From there, once they click on the "Check" button, the JavaScript is meant to loop through the array and check if the value is found within.
If so, a success message is printed, if the value is not found the program prompts the user to try again.

My issue is I am having trouble with looping through the array to find the value. Below is all my code, and I would appreciate the help!

const numbers = [58, 4, 17, 32, 24, 53, 44, 99, 70, 56, 72,
  43, 36, 51, 37, 46, 35, 25, 29, 64, 76, 21,
  82, 94, 47, 12, 19, 31, 69, 81, 20, 91, 50,
  3, 34, 79, 2, 27, 68, 52, 23, 22, 84, 18, 16,
  33, 13, 39, 77, 8
];

let value = document.getElementById("num");
let output = document.getElementById("display");

function printValue() {
  for (let i = 0; i < numbers.length; i++) {
    if (value == i) {
      output.innerHTML = value.value;
      output.innerHTML = "Value was found in the array!"
    }
  }
  output.innerHTML = "Value is not found in array, please try again";

}

value.addEventListener("keyup", function(event) {
  if (event.keyCode === 13) {
    event.preventDefault();
    document.getElementById("sub").click();
  }
})
<h1>Check to see if your value is found in an array</h1>

<label for="num">Enter value:</label>
<input type="text" id="num" name="num">
<br><br>

<button id="sub" onclick="printValue()">Check</button>
<br><br>
<div id="display"></div>

3

Answers


  1. There are few issues in your code:

    1. You are comparing the element with the index where you should compare the element’s value with array value.

    2. You have to return from the function after a match found.

    3. I will also suggest you to convert the value to number and use strict equality (===) operator for checking. I will also suggest you to use textContent instead of innerHTML.

    Try the following way:

    <h1>Check to see if your value is found in an array</h1>
    
    <label for="num">Enter value:</label>
    <input type="text" id="num" name="num">
    <br><br>
    
    <button id="sub" onclick="printValue()">Check</button>
    <br><br>
    <div id="display"></div>
    
    <script>
        const numbers = [58, 4, 17, 32, 24, 53, 44, 99, 70, 56, 72, 
                        43, 36, 51, 37, 46, 35, 25, 29, 64, 76, 21, 
                        82, 94, 47, 12, 19, 31, 69, 81, 20, 91, 50, 
                        3, 34, 79, 2, 27, 68, 52, 23, 22, 84, 18, 16, 
                        33, 13, 39, 77, 8];
    
        let inputEl = document.getElementById("num");
        let output = document.getElementById("display");
        function printValue() {
            let inputElVal = parseInt(inputEl.value); //get the value from the element
            for (let i = 0; i < numbers.length; i++) {
                if (inputElVal === numbers[i]) { //check the input element's value with array value.
                    output.textContent = inputElVal;
                    output.textContent = "Value was found in the array!";
                    return; //return here
                }
            }
            output.innerHTML = "Value is not found in array, please try again";
    
        }
    
        inputEl.addEventListener("keyup", function(event){
            if (event.keyCode === 13) {
                event.preventDefault();
                document.getElementById("sub").click();
            }
        });
    
    </script>

    Though I prefer using Array.prototype.includes() instead for loop:

    The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

    Code Example:

    <h1>Check to see if your value is found in an array</h1>
    
    <label for="num">Enter value:</label>
    <input type="text" id="num" name="num">
    <br><br>
    
    <button id="sub" onclick="printValue()">Check</button>
    <br><br>
    <div id="display"></div>
    
    <script>
        const numbers = [58, 4, 17, 32, 24, 53, 44, 99, 70, 56, 72, 
                        43, 36, 51, 37, 46, 35, 25, 29, 64, 76, 21, 
                        82, 94, 47, 12, 19, 31, 69, 81, 20, 91, 50, 
                        3, 34, 79, 2, 27, 68, 52, 23, 22, 84, 18, 16, 
                        33, 13, 39, 77, 8];
    
        let inputEl = document.getElementById("num");
        let output = document.getElementById("display");
        function printValue() {
            let inputElVal = parseInt(inputEl.value); //get the value from the element
            if (numbers.includes(inputElVal)) {
                output.textContent = "Value was found in the array!";
            } else {
                output.textContent = "Value is not found in array, please try again";
            }
            
        }
    
        inputEl.addEventListener("keyup", function(event){
            if (event.keyCode === 13) {
                event.preventDefault();
                document.getElementById("sub").click();
            }
        });
    
    </script>
    Login or Signup to reply.
  2. In your code you compare the input’s value to the for loop’s index which doesn’t have much sense. We should rather compare an array element.

    There’s a nice method to check whether an array has a value: Array::includes().
    But first we should convert the input’s value to a number and pass it to numbers.includes().
    The problem here that parsing a string to a number is tricky. For example Number(' ') === 0 or parseInt('12asdf') === 12.

    Here’s some parsing options of strings to numbers:
    What is the standard way to check a variable is initialised as a number in javascript?

    So for checking if a string contains only digits we could use a regular expression.
    That could be considered advanced, so check the further easier solutions.

    So our printValue() could be compressed to 2 lines:

    1. Put the messages into an array:
    const messages = ["Value is not found in array, please try again", "Value was found in the array!"];
    
    1. Select an print message with:
    output.innerHTML = messages[+(/^(-?[1-9]+d*|0)$/.test(inputEl.value) && numbers.includes(+inputEl.value))];
    

    Here we

    1. Test if the input contains only digits (with an optional sign and no leading zeros)
    2. If successful test if the input’s values converted with to a number with + (which is the same as Number()) is in the numbers with Array::includes().
    3. Convert the result boolean value to a number with + which will be the index of the corresponding message.
    <h1>Check to see if your value is found in an array</h1>
    
    <label for="num">Enter value:</label>
    <input type="text" id="num" name="num" oninput="printValue()">
    <br><br>
    
    <div id="display"></div>
    
    <script>
        const numbers = [-1, 0, 58, 4, 17, 32, 24, 53, 44, 99, 70, 56, 72, 
                        43, 36, 51, 37, 46, 35, 25, 29, 64, 76, 21, 
                        82, 94, 47, 12, 19, 31, 69, 81, 20, 91, 50, 
                        3, 34, 79, 2, 27, 68, 52, 23, 22, 84, 18, 16, 
                        33, 13, 39, 77, 8];
    
        let inputEl = document.getElementById("num");
        let output = document.getElementById("display");
    
        function printValue() {
            const messages = ["Value is not found in array, please try again", "Value was found in the array!"];
            output.innerHTML = messages[+(/^(-?[1-9]+d*|0)$/.test(inputEl.value) && numbers.includes(+inputEl.value))];
        }
    
    </script>

    But I guess for the OP’s purposes comparing strings is easier to understand.
    We could use Array::some() to compare strings rather than numbers:

    <h1>Check to see if your value is found in an array</h1>
    
    <label for="num">Enter value:</label>
    <input type="text" id="num" name="num" oninput="printValue()">
    <br><br>
    
    <div id="display"></div>
    
    <script>
        const numbers = [-1, 0, 58, 4, 17, 32, 24, 53, 44, 99, 70, 56, 72, 
                        43, 36, 51, 37, 46, 35, 25, 29, 64, 76, 21, 
                        82, 94, 47, 12, 19, 31, 69, 81, 20, 91, 50, 
                        3, 34, 79, 2, 27, 68, 52, 23, 22, 84, 18, 16, 
                        33, 13, 39, 77, 8];
    
        let inputEl = document.getElementById("num");
        let output = document.getElementById("display");
    
        function printValue() {
            const messages = ["Value is not found in array, please try again", "Value was found in the array!"];
            output.innerHTML = messages[+numbers.some(num => num.toString() === inputEl.value)];
        }
    
    </script>

    Regarding the OP’s code it could be fixed as:

    const numbers = [58, 4, 17, 32, 24, 53, 44, 99, 70, 56, 72,
      43, 36, 51, 37, 46, 35, 25, 29, 64, 76, 21,
      82, 94, 47, 12, 19, 31, 69, 81, 20, 91, 50,
      3, 34, 79, 2, 27, 68, 52, 23, 22, 84, 18, 16,
      33, 13, 39, 77, 8
    ];
    
    let value = document.getElementById("num");
    let output = document.getElementById("display");
    
    function printValue() {
      for (let i = 0; i < numbers.length; i++) {
        if (value.value === numbers[i].toString()) {
          output.innerHTML = "Value was found in the array!"
          // here you should return to not allow to print the invalid messages
          return;
        }
      }
      output.innerHTML = "Value is not found in array, please try again";
    
    }
    
    value.addEventListener("keyup", function(event) {
      if (event.keyCode === 13) {
        event.preventDefault();
        document.getElementById("sub").click();
      }
    })
    <h1>Check to see if your value is found in an array</h1>
    
    <label for="num">Enter value:</label>
    <input type="text" id="num" name="num"><button id="sub" onclick="printValue()">Check</button>
    <br><br>
    <div id="display"></div>
    Login or Signup to reply.
  3. Add return

    function printValue() {
      for (let i = 0; i < numbers.length; i++) {
        if (value == i) {
          output.innerHTML = value.value;
          output.innerHTML = "Value was found in the array!"
          return
        }
      }
      output.innerHTML = "Value is not found in array, please try again";
    
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search