如何限制可以在 iPhone 上的 HTML5 数字输入字段中输入的字符数 [英] How to restrict number of characters that can be entered in HTML5 number input field on iPhone

查看:22
本文介绍了如何限制可以在 iPhone 上的 HTML5 数字输入字段中输入的字符数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于以下标记,maxlength"、min"或max"HTML 属性似乎都没有在 iPhone 上产生预期效果:

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"/>

不是限制输入的数字的位数或数值,而是保留在 iPhone 4 上输入的数字.此标记适用于我们测试的大多数其他手机.

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.

是什么?

有什么解决方法吗?

如果它对解决方案很重要,我们使用 jQuery mobile.

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

谢谢!

推荐答案

示例

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);">

如果你使用 jQuery,你可以稍微整理一下 JavaScript:

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">

这篇关于如何限制可以在 iPhone 上的 HTML5 数字输入字段中输入的字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆