我想在我的文本框中限制最多两个数字。但是当一个点(即一个点)出现时,限制必须释放,并且在该点之后它可以扩展到4。
即如果我尝试键入100,则启用限制并限制仅键入最多10个。但如果我键入10.303启用我...
我是jquery的新手。我尝试了很多方法,但它不会起作用。任何帮助都会非常值得关注
答案 0 :(得分:2)
的解决方案:
试试这个: http://jsfiddle.net/Luga5yo4/
$(function () {
$(".txt").on("keyup", function(event) {
// don't handle backspace, delete, pgup/pgdn, home/end, or arrow keys:
if (event.keyCode === 8 || event.keyCode === 46 || event.keyCode >= 33 && event.keyCode <= 40) return false;
var currentEl = $(this);
var value = $(currentEl).val();
// remove letters...
value = value.replace(/[^0-9.-]/g, "");
var hasDecPlace = value.match(/\./);
// separate integer from decimal places:
var pieces = value.split('.');
var integer = pieces[0].replace('-', '');
var decPlaces = ""
if (pieces.length > 1)
{
pieces.shift();
decPlaces = pieces.join('').replace('-', '');
}
// handle numbers greater than 99.9999... :
if (integer > 99.9999 || integer === 99.9999 && parseInt(decPlaces) > 0)
{
integer = "99";
decPlaces = getZeroedDecPlaces(decPlaces);
alert("number must be between 0 and 99");
} // ...and less than 0:
else if (parseInt(integer) < 0)
{
integer = "0";
decPlaces = getZeroedDecPlaces(decPlaces);
alert("number must be between 0 and 99");
}
// handle more than four decimal places:
if (decPlaces.length > 4)
{
decPlaces = decPlaces.substr(0, 4);
alert("number cannot have more than four decimal places");
}
var newVal = hasDecPlace ? integer + '.' + decPlaces : integer;
$(currentEl).val(newVal);
});
function getZeroedDecPlaces(decPlaces) {
if (decPlaces === '') return '';
else if (decPlaces.length === 1) return '0';
else if (decPlaces.length >= 2) return '00';
}
});