目录
<input>标签的type属性跟maxlength属性
金额输入框js处理实例1,2
在<input>
标签中type
属性为number
时maxLength
属性会失效;此时只能用 Js 处理输入框值建议事件使用onInput
、jquery 中 keyup
。type
值为text
时maxLength
恢复效果。
页面代码为:<input type="text" id="ipt1" />
实例1 js代码
$("#ipt1").keyup(function () {
//输入框限制字符长度为10
var len = $(this).val().length > 10 ? $(this).val().slice(0,10) : $(this).val();
$(this).val(len);
var reg = $(this).val().match(/\d+\.?\d{0,2}/);
var txt = '';
if (reg != null) {
//第一个字为零第二个字符不为‘.’
if(reg[0].substring(0,1) === "0" && reg[0].substring(1,2) !== "."){
txt = "0"
} else {
txt = reg[0];
}
}
$(this).val(txt);
}).change(function () {
$(this).keypress();
var v = $(this).val();
if (/\.$/.test(v)){
$(this).val(v.substr(0, v.length - 1));
}
});
实例2
$("#ipt1").keyup(function () {
var input=$(this).val();
if(input.length == 0){
lastAmount=input;
$(this).val("");
return
}
//输入框限制字符长度为10
if(input.length > 10){
$(this).val(input.slice(0,10));
return
}
if(input.match(/^(0|[1-9]\d*)(\.\d{0,2})?$/)){
lastAmount=input;
}else{
$(this).val(lastAmount||'');
}
}).change(function () {
$(this).keypress();
var v = $(this).val();
if (/\.$/.test(v)){
$(this).val(v.substr(0, v.length - 1));
}
});
网友评论