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!
The HTML <input> tag is used to get user input in HTML. To give a limit to the input field, use the min and max attributes, which is to specify a maximum and minimum value for an input field respectively. To limit the number of characters, use the maxlength attribute.
You can specify a minimum length, in characters, for the entered telephone number using the minlength attribute; similarly, use maxlength to set the maximum length of the entered telephone number.
The maxlength attribute defines the maximum number of characters (as UTF-16 code units) the user can enter into an <input> or <textarea> .
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">
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();
}
}
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));
};
});
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