我正在尝试使用 JavaScript 将文本框限制为小数点后两位。该字段也不能以句点开头。
jQuery.fn.ForceCurrencyOnly = function () {
return this.each(function () {
$(this).keypress(function () {
//Only allow period and numbers
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
//Prevent a period being entered first
else if (event.which == 46 && $(this).val().length == 0) {
event.preventDefault();
}
//Only two numbers after a decimal
else if (($(this).val().indexOf('.') != -1) && ($(this).val().substring($(this).val().indexOf('.'), $(this).val().indexOf('.').length).length > 2)) {
event.preventDefault();
}
});
});
};
以上限制输入为数字、单个句点和最多两位小数。我的问题是一旦输入 100.00,该值就无法突出显示并用数字删除。必须删除。
是否有更简单的方法,只允许使用两位小数的货币?
感谢任何帮助。
最佳答案
试试这个:
现场演示: http://jsfiddle.net/oscarj24/8JEF9/
HTML:
Number: <input type="text" id="txt" />
jQuery:
创建一个jQuery函数
以始终以预期格式获取数字
:
jQuery.fn.getNum = function() {
/* trim the string value */
var val = $.trim($(this).val());
/* replace all ',' to '.' if present */
if(val.indexOf(',') > -1) {
val = val.replace(',', '.');
}
/* parse the string as float */
var num = parseFloat(val);
/* use two decimals for the number */
var num = num.toFixed(2);
/* check if 'num' is 'NaN', this will happen
* when using characters, two '.' and apply
* for other cases too.
*/
if(isNaN(num)) {
num = '';
}
return num;
}
然后,使用 .blur(..)
强制文本框
具有预期的值
$(function() { //onReady handler for document
$('#txt').blur(function() { //onBlur handler for textbox
$(this).val($(this).getNum()); //invoke your function, you can use it with other selectors too
});
});
请注意,如果您输入类似 20.129 的内容,您的文本框值将是 20.13 (这意味着该值将被四舍五入)。
我已经测试了许多可能的情况并且工作正常,也许您可以根据需要自定义功能
以用于其他目的。
关于javascript - Javascript 中将文本框限制为小数点后两位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23567676/