How to restrict number of characters that can be entered in HTML5 number input field on iPhone
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();
}
}
According to MDN, maxlength
is not used for number
s. Have you tried just:
<input type="number" min="0" max="99" />
OR
<input type="range" min="0" max="99" />