Input Only Numbers: HTML & JavaScript Guide
You can use the following method to set up input that only allows numbers:
- Utilize the HTML input tag and set the type attribute to “number”, for example:
<input type="number" name="quantity">
This will only allow users to input values of numeric type.
- Use event listeners in JavaScript to check if the input content is a number, and add the corresponding handling logic in the keyup or keydown events of the input box.
<input type="text" id="numericInput">
const numericInput = document.getElementById('numericInput');
numericInput.addEventListener('keyup', function(event) {
const value = event.target.value;
event.target.value = value.replace(/[^0-9]/g, '');
});
This will instantly replace non-numeric characters with empty strings as the user inputs.
- Use regular expressions in JavaScript to validate the input content as a number, and display an error message when necessary. For example:
<input type="text" id="numericInput">
<div id="errorText"></div>
const numericInput = document.getElementById('numericInput');
const errorText = document.getElementById('errorText');
numericInput.addEventListener('keyup', function(event) {
const value = event.target.value;
if (!/^[0-9]*$/.test(value)) {
errorText.innerHTML = '只能输入数字';
} else {
errorText.innerHTML = '';
}
});
This will validate input in real-time to check if it is a number and display an error message if necessary when the user inputs it.
Please note that these methods only validate user input on the front end, for security and correctness, you also need to validate and process data on the backend.