1

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;

3 Answers3

5

know that document.getElementsByClassName(...) returns a HTMLCollection regardless of whether there is only one element or more.

what you want is this:

var num = input[0].value;

note - typically, if you want to target only one element, you should use an id attribute on that element and then use document.getElementById(...) to retrieve the value of the element.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
3

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!

Joshua Russell
  • 670
  • 5
  • 13
0

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.

Tim Erickson
  • 582
  • 5
  • 15