5

Im trying to limit to X number the characters in a input (type of number). ive tried a lot of options and none seems to work. I dont want to use the option tel as it needs the numeric keyboard on a mobile device (yes, with ., and all the symbols) I tried also the pattern solution but it only worked for iOS, didnt work in android (displayed the normal keyboard).

The best way would be that if the user hits the limit dont let him type anymore, if he wants to highlight the text and re-type a different number he is allow to. Just not let him type more than the specified number of characters.

So, any help is appreciated.

marsalal1014
  • 1,897
  • 3
  • 17
  • 24
  • Use `maxlength` property in your `` tag. – Sandeep Nayak Feb 28 '14 at 05:18
  • 1
    that would be great! if maxLenght would be supported by number type. in HTML5 the input type of number doesnt have this property. – marsalal1014 Feb 28 '14 at 05:20
  • possible duplicate of [Limit number of characters allowed in form input text field](http://stackoverflow.com/questions/8545376/limit-number-of-characters-allowed-in-form-input-text-field) – Brett DeWoody Feb 28 '14 at 05:20
  • 3
    Not duplicated! I need to be TYPE="NUMBER" not text. – marsalal1014 Feb 28 '14 at 05:23
  • 1
    I stand corrected, not a duplicate. – Brett DeWoody Feb 28 '14 at 05:29
  • @marsalal1014 does your browser supports HTML 5 ?? this code seems working for me – Dimag Kharab Feb 28 '14 at 05:40
  • it does. Latest Chrome. The problem with that is it doesnt handle if the user stars typing the numbers he want instead using the toggle buttons that comes with the input. if I start typing 1234567789 it will let me put as many numbers as I want – marsalal1014 Feb 28 '14 at 05:42
  • It will allow you to type as many numbers as you want but if you try to submit the form it will throw an error saying the number has to be within the range you set in the min and max attributes. – Brett DeWoody Feb 28 '14 at 05:48
  • not using a form, is a couple of inputs that do a calculation and throw a result. Calculation is made in the jquery code – marsalal1014 Feb 28 '14 at 05:54
  • You should look at `oninput` and `onchange` events, so you can trim the input string as needed. – FonzTech Jan 10 '20 at 12:14

13 Answers13

8

Note: charCode is non-standard and deprecated, whereas keyCode is simply deprecated.

Check this code

JavaScript

<script>
function check(e,value)
{
    //Check Charater
    var unicode=e.charCode? e.charCode : e.keyCode;
    if (value.indexOf(".") != -1)if( unicode == 46 )return false;
    if (unicode!=8)if((unicode<48||unicode>57)&&unicode!=46)return false;
}
function checkLength()
{
    var fieldLength = document.getElementById('txtF').value.length;
    //Suppose u want 4 number of character
    if(fieldLength <= 4){
        return true;
    }
    else
    {
        var str = document.getElementById('txtF').value;
        str = str.substring(0, str.length - 1);
        document.getElementById('txtF').value = str;
    }
}

and HTML input with number type below

onInput //Is fired also if value change from the side arrows of field in Chrome browser

<input id="txtF" type="number" onKeyPress="return check(event,value)" onInput="checkLength()" />

Fiddle Demo

Update -- Little bit generic code example

Change above function into this one

function checkLength(len,ele){
  var fieldLength = ele.value.length;
  if(fieldLength <= len){
    return true;
  }
  else
  {
    var str = ele.value;
    str = str.substring(0, str.length - 1);
    ele.value = str;
  }
}

In HTML use like this

<!-- length 4 -->    
<input id="txtF" type="number" onKeyPress="return check(event,value)" onInput="checkLength(4,this)" />
<!-- length 5 -->    
<input  type="number" onKeyPress="return check(event,value)" onInput="checkLength(5,this)" />
<!-- length 2 -->    
<input  type="number" onKeyPress="return check(event,value)" onInput="checkLength(2,this)" />

Demo

oldboy
  • 5,729
  • 6
  • 38
  • 86
Blu
  • 4,036
  • 6
  • 38
  • 65
  • It helped me too. Thx @Blu – Ram Aug 06 '18 at 09:48
  • Still allows to enter at start and middle, removing the last char. – Ronald Dsouza Jan 08 '19 at 07:13
  • @RonaldDsouza Yes because it was not a requirement in question. But if you don't want to allow in start or middle also then see **YashPatel** answer if it can fits on your requirement https://stackoverflow.com/a/22088379/2385565 – Blu Jan 12 '19 at 00:51
  • @Blu No it doesn't fit. If I input 9999999999(length of 10 numbers), I am still able to press the up arrow and take that digit to 10000000000(11 numbers) – Ronald Dsouza Jan 15 '19 at 07:26
  • @RonaldDsouza You can off that spinners by using css. Updated fiddle http://jsfiddle.net/ys1d7xpr/ . Otherwise its better if you start a new question with all your requirements. Your requirements different then the current OP requirement. – Blu Jan 16 '19 at 08:37
6

Another option - the tel input type abides by the maxlength and size attributes.

<input type="tel" size="2" maxlength="2" />

<input type="tel" size="10" maxlength="2" />
Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184
  • Yes that would be the best way to go, if, I would need the "." symbols. Its like a weight calculator, the user can enter 123.3 pounds or 123 pounds. If I use "tel" on the mobile devices the keyboard that it will show up is the telephone one, with out "." option. – marsalal1014 Feb 28 '14 at 06:03
2

May be it will be useful.

Here is field to input Patient Age. It allows to input 3 numbers only.

HTML

<input autocomplete="off" class="form-control"  id="Patient_Age" max="150" maxlength="3" name="PatientAge" placeholder="Age" size="3" type="number" value="0">

JS

<script>
    $(function () {         
        $("#Patient_Age").keydown(function (e) {
            // Allow: backspace, delete, tab, escape, enter  
            if ($(this).val().length <= 2 || $.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
                // Allow: Ctrl+A
                // (e.keyCode == 65 && e.ctrlKey === true) ||
                // Allow: home, end, left, right
                (e.keyCode >= 35 && e.keyCode <= 39)) {
                // let it happen, don't do anything
                return;
            }
            else {
                event.preventDefault();
            }
            // Ensure that it is a number and stop the keypress
            if ($(this).val().length <= 2 || (e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                e.preventDefault();
            }
            else {
                event.preventDefault();
            }
        });
    }); // end of $

</script>
NoWar
  • 36,338
  • 80
  • 323
  • 498
1

The HTML5 number type input has min and max attributes.

If you wanted to limit the number of characters to 1 you could set a min of 0 and a max of 9.

You can also set the step attribute, which is 1 by default, but would come in use if you wanted the ability to select decimals or other rounded numbers.

<input type="number" maxlength="1" max="9" min="1" size="1" />

Here's the full demo

Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184
  • But it doesn't support in all browsers – Sarath Feb 28 '14 at 05:28
  • that might work, if only the user wont type in the input. Works only if hits the arrow at the end of the input – marsalal1014 Feb 28 '14 at 05:30
  • As Sarath pointed out the `number` type isn't supported in all browsers. Without using JavaScript (which you could certainly do) the best option might be using `maxlength`, `min` and `max`. Browsers that don't support the `number` type would then fallback to the `text` type and the `maxlength` limit. – Brett DeWoody Feb 28 '14 at 05:33
  • again, this could work only if the user doesnt type the number in the input. you can type as many number as you want – marsalal1014 Feb 28 '14 at 05:49
0

please review this code

<script language="javascript" type="text/javascript">
function limitText(limitField, limitCount, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    } else {
        limitCount.value = limitNum - limitField.value.length;
    }
}
</script>

<form name="myform">
<input name="limitedtextfield" type="text" onKeyDown="limitText(this.form.limitedtextfield,this.form.countdown,15);" 
onKeyUp="limitText(this.form.limitedtextfield,this.form.countdown,15);" maxlength="15"><br>
<font size="1">(Maximum characters: 15)<br>
You have <input readonly type="text" name="countdown" size="3" value="15"> characters left.</font>
</form>
Karthick Kumar
  • 2,349
  • 1
  • 17
  • 30
0

I think this requires the onkeyup event handler.

Use this handler to keep on entering numbers till 5 keyup's are encountered. After this , don't let the the number to be entered by returning a 0, unless key pressed is backspace or delete .

rahulmishra
  • 620
  • 1
  • 13
  • 29
0

You can try thiss jQuery code :

In HTML

<input type="number" id="number" />

In JS

$(document).ready(function () {
    var element = document.getElementById('number');

    $("#number").keydown(function (event) {
        // Allow only backspace and delete

        if($(this).val().length <= 9 || event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 )
        {
            if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9) {
                // let it happen, don't do anything
            } else {
                // Ensure that it is a number and stop the keypress
                if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
                    event.preventDefault();
                }
            }
        }else{

            event.preventDefault();
        }          

    });


});

I have not any idea wheather its working on IOS N Android but its work on all browser.

DEMO

YashPatel
  • 295
  • 1
  • 2
  • 9
0

For Decimal values, lets say "25.2" code is as under.

if(thisObj.value.indexOf(".") >=0)
{
    if(fieldLength <= 4)
    {
        return true;
    }
    else
    {
        var str = thisObj.value;
        str = str.substring(0, str.length - 1);
        thisObj.value = str;
    }
}
else
{
    if(fieldLength <= 2)
    {
        return true;
    }
    else
    {
        var str = thisObj.value;
        str = str.substring(0, str.length - 1);
        thisObj.value = str;
    }
}
Atul
  • 39
  • 2
0

You can easily do it like this,

<input type="text" pattern="\d*" maxlength="4">
Hasini
  • 3
  • 3
0

Proper way 2020 for type number is to check on keydown validation and it should work like this: onkeypress="checkValidation(fieldValue);" <-- on input in html and in js:

checkValidation(a) {
    if (`${a}`.length < 8) {
        return true;
    } else {
        return false;
    }
}
DanielWaw
  • 669
  • 7
  • 22
-1

Use the maxlength property like this.

<input type="text" maxlength="5"/>
GP12
  • 120
  • 7
  • 1
    yes, but I need to be type="number" and in html5 it doesnt have this property. I need to be number as I have to get the numeric keyboard in a mobile device. – marsalal1014 Feb 28 '14 at 05:22
  • Use this link this might be useful to you http://stackoverflow.com/questions/2808184/restricting-input-to-textbox-allowing-only-numbers-and-decimal-point – GP12 Feb 28 '14 at 06:17
-1

Dude why go for javascript? Just try

<input type="text" maxlength="4" size="4">

maxlength will anyways define a maximum length for the input field.

Hope this solved the problem :)

EDIT: Since you specifically want numbers, why dont you use the above and then run a jquery validation to check for numbers? That will also work..

EDIT: Okay, try

<input type="number" name="pin" min="1000" max="9999">
kunl
  • 1,177
  • 1
  • 15
  • 25
-2

Did you try the property maxlength ?

<input type="text" maxlength="5" name="user" >
Sarath
  • 608
  • 4
  • 12