javascript 在Javascript中将文本框限制为两位小数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23567676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Restrict text box to two decimal places in Javascript
提问by ministrymason
I am trying to restrict a text box to two decimal places using JavaScript. The field also cannot start with a Period.
我正在尝试使用 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();
}
});
});
};
};
The above restricts the input to numbers, a single period and a maximum of two decimal places. My problem is once 100.00 is entered, the value cannot be highlighted and removed with a number. It has to be deleted.
以上将输入限制为数字、单个句点和最多两位小数。我的问题是一旦输入 100.00,该值就不能用数字突出显示和删除。它必须被删除。
Is there a simpler way of only allowing a currency with two decimal places?
有没有更简单的方法只允许带有两位小数的货币?
Any help appreciated.
任何帮助表示赞赏。
回答by Oscar Jara
Try this:
试试这个:
Live Demo:http://jsfiddle.net/oscarj24/8JEF9/
现场演示:http : //jsfiddle.net/oscarj24/8JEF9/
HTML:
HTML:
Number: <input type="text" id="txt" />
jQuery:
jQuery:
Create a jQueryfunction
to always get a number
in the expected format:
创建一个jQueryfunction
以始终获得number
预期格式的 a:
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;
}
Then, force the textbox
to have the expected value
using .blur(..)
然后,强制使用textbox
预期的value
.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
});
});
Just to know, if you put something like 20.129, your textbox value will be 20.13(this means that the value will be rounded).
只是想知道,如果你输入类似20.129 的东西,你的文本框值将是20.13(这意味着该值将被四舍五入)。
I've tested many possible situations and works fine, maybe you can customize the function
as you wish for other purposes.
我已经测试了许多可能的情况并且工作正常,也许您可以根据需要自定义function
其他用途。
回答by thispatchofsky
How about applying a RegEx validation :
如何应用正则表达式验证:
<input type="text" pattern="^[0-9]*\.[0-9]{2}$" />
Hope this helps!
希望这可以帮助!
回答by Faraz
Just check if entered key is not backspace in final check
只需在最终检查中检查输入的键是否不是退格键
jQuery.fn.ForceCurrencyOnly = function() {
return this.each(function() {
$(this).keypress(function(event) {
console.log(event.which);
//Only allow period and numbers
//Only allow period and numbers
if (event.which != 8 && (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 ( event.which != 8 && (event.which < 48 || event.which > 57) && ($(this).val().indexOf('.') != -1) && ($(this).val().substring($(this).val().indexOf('.'), $(this).val().indexOf('.').length).length > 2)) {
event.preventDefault();
}
});
});
};
回答by Sunil
try this..
试试这个..
jQuery.fn.getNum = function() {
var val = $.trim($(this).val());
if(val.indexOf(',') > -1) {
val = val.replace(',', '.');
}
var num = parseFloat(val);
var num = num.toFixed(1);
if(isNaN(num)) {
num = '';
}
return num;
}
$(function() {
$('#txt').keyup(function() {
$(this).val($(this).getNum());
});
});
回答by Mike Clark
$("#YourtxtId").keypress(function () {
var txt = $("#YourtxtId").val();
if (txt.indexOf(".") > -1 && txt.split(".")[1].length > 1) {
var substr = txt.split(".")[1].substring(0, 1);
$("#YourtxtId").val(txt.split(".")[0] + "." + substr);
}