-6

I am unsure on how to create an input box that only allows integers to be inputted. I have made a HTML version of the input but I need the same input type within JavaScript.

Here's my current HTML input

<input type="text" autocomplete="off" ondragstart="return false;" ondrop="return false;" onpaste="return false;" onkeypress="return event.charCode >= 48 && event.charCode <= 57;">Amount</input>
Moo
  • 166
  • 12

2 Answers2

2

You should change type="text" to type="number". You might also be interested in setting values for the min, max, and step attributes as well.

var input_element = document.getElementById('input');
var output_element = document.getElementById('output');

document.getElementById('form').addEventListener('input', function (event) {
    output_element.value = input_element.value;
});
<form id="form">
    <label for="input">Input:</label>
    <input id="input" type="number" min="0" max="10" step="2" />

    <br />

    Output: <output id="output" for="input"></output>
</form>
Tyler Crompton
  • 12,284
  • 14
  • 65
  • 94
0

You can use input of type number and step attribute:

<input type="number" step="1">

This way the input can only take integer values.

Michał Miszczyszyn
  • 11,835
  • 2
  • 35
  • 53