How to get value from input type = number?

时间:2017-04-10 01:45:16

标签: javascript html input

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;

2 个答案:

答案 0 :(得分:3)

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.

答案 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!