I want to re-create this above shown design using an Input field. However, the user should be able to enter only one numeric digit per box. How can I restrict the user to enter only 1 digit per input box. Please suggest.
Edit: this solution solves most of the problem, but does not restrict the input to digits.
Complete HTML/CSS Course 2022 To limit an HTML input box to accept numeric input, use the <input type="number">. With this, you will get a numeric input field. After limiting the input box to number, if a user enters text and press submit button, then the following can be seen “Please enter a number.”
Firstly, create an array that stores all the ASCII codes or values of the digits 0 (ASCII value 48) through 9 (ASCII value 57) so that the input in the textbox can be validated later on. Next, set the max length of the input to 10 using maxlength attribute of the input tag.
You can use the <input> tag with attribute type='number'. This input field allows only numerical values. You can also specify the minimum value and maximum value that should be accepted by this field.
By default, HTML 5 input field has attribute type=”number” that is used to get input in numeric format. Now forcing input field type=”text” to accept numeric values only by using Javascript or jQuery. You can also set type=”tel” attribute in the input field that will popup numeric keyboard on mobile devices.
Use the maxlength and the pattern to allow only one number
<input type="text" maxlength="1" oninput="this.value=this.value.replace(/[^0-9]/g,'');" />
I would use the number input type, and use max and min. So this should work:
<input type="number" min="0" max="9" step="1">
You could use the focusout
jquery script to check the value isn't greater than 9.
$(document).ready(function() {
$('input').focusout(function() {
var max = $(this).val();
if (max > 9) {
$(this).val("9");
alert("Maximum is 9");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" max="9" Min="0" />
<input type="number" max="9" Min="0" />
<input type="number" max="9" Min="0" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With