'How to get value from input type = number?

Problem

So my problem is that I have an <input type='number'>, and I'm trying to get the value of the input when the user clicks enter and console.log() the value. But when I tested, it returned undefined.

Input

<input type="number" value="0" placeholder="Enter Number..." class="insert">

JavaScript

function main() {

        var input = document.getElementsByClassName('insert');

        document.addEventListener('keydown', function(e) {
            if(window.event == 13 || e.which == 13) {

                var num = input.value;

                console.log(num)

                /*if(num < 0) {
                    alert('Please enter a positive number');
                }*/

            }
        })

    }

    window.onload = main;


Solution 1:[1]

The problem is that you're selecting the inputs with getElementsByClassName. This will return a HTMLCollection (essentially an Array).

To avoid this, you can either use getElementById or use input[0].value which will get the value of the first item in the collection. Given it's a single input, this will work, however not the best approach.

If you have multiple inputs, you would need to loop. For example

var inputs = document.getElementsByClassName('insert');

for(var i = 0; i < inputs.length; i++) {
  console.log(inputs[i].value);
}

Hope that helps!

Solution 2:[2]

What they said, plus note: you're using <input type="number"> but when you get that .value, it's going to be a string. Your num < 0 comparison will work, but other operations might produce unwanted results.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joshua Russell
Solution 2 Tim Erickson