user7627319
user7627319

Reputation:

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;

Upvotes: 1

Views: 11433

Answers (3)

Tim Erickson
Tim Erickson

Reputation: 592

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.

Upvotes: 1

Ousmane D.
Ousmane D.

Reputation: 56413

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.

Upvotes: 5

Joshua Russell
Joshua Russell

Reputation: 700

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!

Upvotes: 3

Related Questions