How to restrict number of characters that can be entered in HTML5 number input field on iPhone
Asked Answered
E

12

31

It seems that neither of the "maxlength", "min" or "max" HTML attributes have the desired effect on iPhone for the following markup:

 <input type="number" maxlength="2" min="0" max="99"/>

Instead of limiting the number of digits or the value of the number entered, the number is just left as it was typed in on iPhone 4. This markup works on most other phones we tested.

What gives?

Any workarounds?

If it is important to the solution, we use jQuery mobile.

Thanks!

Endicott answered 23/3, 2012 at 14:53 Comment(0)
H
52

Example

JS

function limit(element)
{
    var max_chars = 2;
         
    if(element.value.length > max_chars) {
        element.value = element.value.substr(0, max_chars);
    }
}

HTML

<input type="number" onkeydown="limit(this);" onkeyup="limit(this);">

If you are using jQuery you can tidy up the JavaScript a little:

JS

var max_chars = 2;
    
$('#input').keydown( function(e){
    if ($(this).val().length >= max_chars) { 
        $(this).val($(this).val().substr(0, max_chars));
    }
});
    
$('#input').keyup( function(e){
    if ($(this).val().length >= max_chars) { 
        $(this).val($(this).val().substr(0, max_chars));
    }
});

HTML

<input type="number" id="input">
Higbee answered 18/5, 2012 at 16:44 Comment(4)
Hi! This method is working fine, if I restrict user up to 1/2/3 characters, but as soon as I go to the limit of 4 or above, the solution breaks. I guess the problem is because of addition of ',' in the number field, but not sure. Can you please check this solution for 4 or more characters.Dinodinoflagellate
Sadly, I ended up relying on javascript/jQuery for this. I couldn't use type="range" because that has a different semantic.Endicott
Not on keydown : else no copy/pasteNibble
Use substring() instead of substr(), developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/….Tarnish
H
6

you can use this code:

<input type="number" onkeypress="limitKeypress(event,this.value,2)"/>

and js code:

function limitKeypress(event, value, maxLength) {
    if (value != undefined && value.toString().length >= maxLength) {
        event.preventDefault();
    }
}
Hadwin answered 30/4, 2016 at 7:48 Comment(2)
Thanks, Buddy @Hadwin Btw Why we need maxlength="2" min="0" max="99" here ...?? With out them it Works Fine i guess :)Creativity
maxlength attr do not work in input with type="number"Hadwin
B
3

Another option with jQuery, but onkeypress event... ;)

$("input[type=number]").on('keypress',function(e) { 
    var $that = $(this),
    maxlength = $that.attr('maxlength')
    if($.isNumeric(maxlength)){
        if($that.val().length == maxlength) { e.preventDefault(); return; }

        $that.val($that.val().substr(0, maxlength));
    };
});
Burweed answered 18/8, 2014 at 22:41 Comment(1)
This should be the accepted answer!Link
F
2

According to MDN, maxlength is not used for numbers. Have you tried just:

<input type="number" min="0" max="99" />

OR

<input type="range" min="0" max="99" />
Fritzfritze answered 24/3, 2012 at 3:58 Comment(2)
late to the game but how did this get 4 upvotes? deffo doesn't workRhumb
@TheWalrus but it does.Link
C
2

Check this out, it works for me;

Is there a minlength validation attribute in HTML5?

Conjoint answered 26/11, 2013 at 6:4 Comment(1)
pattern=".{4,4}" : GreatNibble
C
1

as Andrew said you need to change the type to range, beside that you are going to have problems with IE and FF and probably old ipad browser because that's from HTML 5, and it's a "Kind New". Take a look to this person who tried the range with JS, Specify range of numbers to input in number field using javascript

Colman answered 17/4, 2012 at 16:3 Comment(0)
P
1

You can use JavaScript to check how many characters are in the box and if there are too many, remove one: http://www.webcodingtech.com/javascript/limit-input-text.php

Pinkham answered 12/5, 2012 at 10:13 Comment(0)
B
1

Here a more optimized jQuery version that caches the selectors. It also uses the maxlength attribute that is not supported by input type number.

// limits the input based on the maxlength attribute, this is by default no supported by input type number
$("input[type=number]").on('keydown keyup',function(){ 
    var $that = $(this),
    maxlength = $that.attr('maxlength')
    if($.isNumeric(maxlength)){
        $that.val($that.val().substr(0, maxlength));
    };
});
Burgle answered 23/9, 2013 at 6:58 Comment(0)
W
1

I use input event listener

var storeName = document.getElementById('storeName')
var storeNameCounter = document.getElementById('storeNameCounter')       
    storeName.addEventListener('input', (event) => {
        var max_chars = 50         
        if(event.target.value.length > max_chars) {
        event.target.value = event.target.value.substr(0, max_chars)
        }
        storeNameCounter.innerHTML = `${event.target.value.length}/50`       
    })
<input type="text" 
    id="storeName"
    name="store_name" 
    class="store_name"
    placeholder="store name" 
    x-moz-errormessage="This field should not be left blank." 
    maxlength="500" required>   
<span id="storeNameCounter" class="store_name_counter">0/50</span>  
Wyrick answered 8/6, 2023 at 0:40 Comment(1)
By far the best answerHobo
S
0

I know this question is one year old, but I don't prefer the selected answer. Because the way it works is that it shows the character that is typed and then removes it.

In contrast I will propose another way which is similar to Will's, it is just better in the way that it prevents the character from being shown. Also I've added an else if block to check if the character is a number and then it is a good function to validate the number fields.

HTML

<input type="number" onkeydown="limit(this);">

JS

function limit(element)
{
    var max_chars = 2;
    if (arguments[1].char !== "\b" && arguments[1].key !== "Left" && arguments[1].key !== "Right") {
        if (element.value.length >= max_chars) {
            return false;
        } else if (isNaN(arguments[1].char)) {
            return false;
        }
    }
}
Stelle answered 14/8, 2013 at 21:6 Comment(0)
D
0

This is Tripex answer optimized for allowing delete key, works when typing and on paste.

$(document).on("keyup", "#your_element", function(e) {
    var $that = $(this),
    maxlength = $that.attr('maxlength');
    if ($.isNumeric(maxlength)){
        if($that.val().length === maxlength) {
            e.preventDefault();
            // If keyCode is not delete key 
            if (e.keyCode !== 64) {
                return;
            }
        }
        $that.val($that.val().substr(0, maxlength));
    }
});
Debbydebee answered 15/8, 2017 at 15:6 Comment(0)
A
0

My solution using jQuery:

JS

function maxlength(event)
{
    const ele = event.target;
    const maxlength = ele.maxLength;
    const value = ele.value;
    if (event.type == 'keypress')
    {
        if (value.length >= maxlength)
        {
            event.preventDefault();
        }
    }
    else if (event.type == 'keyup')
    {
        if (value.length > maxlength)
        {
            ele.value = value.substring(0, maxlength);
        }
    }
}

$('input[type=number][maxlength]').on('keypress keyup', maxlength);

HTML

<input type="number" maxlength="2">
Apostil answered 3/6, 2021 at 16:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.