Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input field - Restrict to One digit [closed]

Tags:

html

css

expected UI

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.

like image 330
Sijo Jose Avatar asked Feb 06 '17 12:02

Sijo Jose


People also ask

How do I restrict a number in input field?

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.”

How do I restrict only 10 numbers in a text box in HTML?

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.

How do I restrict input only numbers in HTML?

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.

Can you restrict the textbox to input numbers only?

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.


3 Answers

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,'');" />
like image 137
Pablo Salcedo T. Avatar answered Oct 26 '22 00:10

Pablo Salcedo T.


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">
like image 32
Mike Harrison Avatar answered Oct 26 '22 00:10

Mike Harrison


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" />
like image 27
jbutler483 Avatar answered Oct 25 '22 23:10

jbutler483