4

This is a text-field. See..I set the maxlength property to 10. So, only 10 characters can be entered

<input maxlength="10" id="txt_name" name="txt_name" type="text" required="required"/>

This is a number field. I want this also to have maxlength of 10 so that the users can enter their 10 digit mobile number. This restricts users to enter additional numbers.

 <input id="txt_mob" name="txt_mob" type="number" maxlength="10"/>

But the maxlength doesnpt work with number fields. Why?? Is there any way to do this without using Javascript or jQuery?

Here's a FIDDLE.

5 Answers5

1

the number type doesnt accept the attribute maxlength. you can try this

put the type to text and use this.

this script only accept numbers input, put it in the head of your page.

<script>
function isNumber(event) {
  if (event) {
    var charCode = (event.which) ? event.which : event.keyCode;
    if (charCode != 190 && charCode > 31 && 
       (charCode < 48 || charCode > 57) && 
       (charCode < 96 || charCode > 105) && 
       (charCode < 37 || charCode > 40) && 
        charCode != 110 && charCode != 8 && charCode != 46 )
       return false;
  }
  return true;
}
</script>

then use this at your input field

onkeydown="return isNumber(event);"

example

<input type="text" onkeydown="return isNumber(event);" maxlength="10" />
ruben450
  • 140
  • 2
  • 10
  • I know this code. I have this with me. I use it everytime. But what if the JavaScript is disabled in user's browser?? @ruben450 –  Oct 09 '14 at 10:08
1

From mdn,

If the value of the type attribute is text, email, search, password, tel, or url, this attribute specifies the maximum number of characters (in Unicode code points) that the user can enter; for other control types, it is ignored.

So maxlength is ignored on

     <input type="number">

by design. So, you can use a regular text input and enforce validation on the field with the new pattern attribute

     <input type="text" pattern="([0-9]{3})" maxlength="4">

Hope it helps some what...

SDK
  • 1,532
  • 1
  • 15
  • 31
0

For input number, you need to use min/max property :

<input type="number" id="txt_mob" name="txt_mob" min="1" max="5">

You can see an example on the w3schools website:

http://www.w3schools.com/tags/att_input_max.asp

Bonomi
  • 2,541
  • 5
  • 39
  • 51
ghorg12110
  • 36
  • 6
0

For input elements of type number you can't use the maxlength, that attribute is for strings only. For numbers you can use the min="0" and max="10". You can see an example here:

http://www.w3schools.com/tags/att_input_max.asp

Bonomi
  • 2,541
  • 5
  • 39
  • 51
0

You can use <input type="number" name="quantity" min="1" max="9999999999">

BlackBlaze
  • 254
  • 2
  • 10