如何限制输入文本框,限制:
答案 0 :(得分:1)
以下是代码:
<强> HTML 强>:
<input type="text" id="main"></input>
<强>的Javascript 强>:
var main = document.getElementById('main');
main.onkeydown = codeFunc;
function codeFunc(e) {
var code = e.which || e.keyCode;
var value = e.currentTarget.value;
var letter = String.fromCharCode(code);
codeFunc.isNegative = value.indexOf("-") > -1;
codeFunc.isMiddle = value.length != 0;
var letter = String.fromCharCode(code);
if (letter == "-" && !codeFunc.isNegative && !codeFunc.isMiddle) {
codeFunc.isMiddle = true;
codeFunc.isNegative = true;
return true;
} else if (letter == "¾" && !codeFunc.isDecimal) {
codeFunc.isMiddle = true;
codeFunc.isDecimal = true;
return true;
}
var test = /[\d\b]+/.test(letter);
if (!codeFunc.isMiddle) {
codeFunc.isMiddle = test;
return codeFunc.isMiddle;
}
return test;
}
<强> JSFIDDLE 强>
答案 1 :(得分:0)
您可以使用正则表达式验证文本框的keydown事件的输入:
<强> REGEX 强>
/^-?\d{2}(\.\d+)?$/
作为旁注,对JavaScript和jQuery进行一些研究。