Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

301
Views
JS indexOf() not giving result of inputted number

I am trying to see the indexOf() of an array of numbers for an inputted value.

For regular numbers in the array it is not working, but if the number in the array uses quotes (such as "3"), it somehow works.

Why is this not working for a regular number without quotes?

<p><input type="number" id="inNum"></p>
<button onclick="indexCheck()">Check</button>
<p id="result"></p>

<script>
var arr = [1, 2, "3", 4];

function indexCheck() {
    var x = document.getElementById("inNum").value;
    
    var ind = arr.indexOf(x);

    document.getElementById("result").innerHTML = ind;
    };
</script>

In the above example, 1, 2, and 4 give a result of -1 (so they are not found in the array) but 3 give result of 2 (so it is found in the array at position 2).

Yet somehow a non-inputted number can be found and it works fine:

<button onclick="indexCheck()">Check</button>
<p id="result"></p>

<script>
var arr = [1, 2, "3", 4];

function indexCheck() {
    var x = 2;
    
    var ind = arr.indexOf(x);

    document.getElementById("result").innerHTML = ind;
    };
</script>

What am I doing wrong? Any help would be appreciated!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Your input "number" is actually a string. Here's documentation of the HTMLInputElement interface; note that the value property is of type string.

So that's why it can find the value "3" in your array, but not the number 3. In order to convert it to a number, you can use the Number global function:

var string = "3";
var number = Number(string); // will be 3
about 4 years ago · Juan Pablo Isaza Report

0

<script>
    var arr = ['1', '2', '3', '4'];
    function indexCheck() {
        var x = document.getElementById("inNum").value;
        var ind = arr.indexOf(x);

        document.getElementById("result").innerHTML = ind
    }
</script>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!