mar*_*014 4 html javascript jquery html5
我试图将X数字限制为输入中的字符(数字类型).香港专业教育学院尝试了很多选择,似乎没有工作.我不想使用选项tel,因为它需要移动设备上的数字键盘(是的,带.,和所有符号)我也试过模式解决方案,但它只适用于iOS,没有在android中工作(显示正常键盘).
最好的方法是,如果用户达到限制,不要再让他输入,如果他想突出显示文本并重新输入他允许的不同数字.只是不要让他输入超过指定数量的字符.
所以,任何帮助表示赞赏.
检查此代码
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;
}
}
Run Code Online (Sandbox Code Playgroud)
和HTML charCode
与keyCode
下面类型
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()" />
Run Code Online (Sandbox Code Playgroud)
更新 - 一点点通用代码示例
将上述功能改为此功能
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;
}
}
Run Code Online (Sandbox Code Playgroud)
在HTML中使用像这样
<!-- 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)" />
Run Code Online (Sandbox Code Playgroud)
另一种选择 -tel
输入类型遵守maxlength
和size
属性。
<input type="tel" size="2" maxlength="2" />
Run Code Online (Sandbox Code Playgroud)
<input type="tel" size="2" maxlength="2" />
Run Code Online (Sandbox Code Playgroud)