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;
1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Be careful when you say that it returns an Array. It returns a HTMLCollection, not an array.
@Marty sure thing, I'll add that. Thanks for letting me know.
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!

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.