String.prototype.count = function (c) {
var sum = 0;
for (var i = 0; i < this.length; i++) {
if (this[i] == c) { sum++; }
}
return sum;
};
$(".decimal-2-dig").keydown(function (event) {
var isDot = function() {
return (event.keyCode == 110 || event.keyCode == 190);
}
var isValidKeyCode = function() {
if (event.shiftKey || event.ctrlKey || event.altKey) { return false; }
var isPass = false;
if (event.keyCode >= 96 && event.keyCode < 106) { isPass = true; }
if (event.keyCode >= 48 && event.keyCode < 58) { isPass = true; }
if (isDot()) { isPass = true; }
if (event.keyCode == 8) { return true; }
return isPass;
};
if (!isValidKeyCode()) {
return false;
}
var v = $(this).val();
if (v.count('.') > 0 && isDot()) { return false; }
if (v.indexOf('.') != -1 && event.keyCode != 8 /*back space*/) {
var val = $(this).val();
var selectStr = window.getSelection().toString();
if (selectStr != "") {
return isValidKeyCode();
}
$(this).val(val.substr(0, val.indexOf('.') + 2));
}
});
使用
<input class="decimal-2-dig" /