使用 jquery 只允许 2 个小数点输入到文本框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17083965/
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
Allow only 2 decimal points entry to a textbox using jquery?
提问by R J.
Allow only 2 decimal points when entering number to a textbox using jquery.
使用 jquery 在文本框中输入数字时只允许 2 个小数点。
Please suggest any regex to allow only two decimal in textbox.
请建议任何正则表达式在文本框中只允许两位小数。
I have tried the following code.
我试过下面的代码。
$("#amountId").val().replace (/(\.\d\d)\d+|([\d.]*)[^\d.]/, '');
回答by A. Wolff
You could do it without regex:
你可以在没有正则表达式的情况下做到这一点:
var dec = parseFloat($("#amountId").val(),10).toFixed(2);
回答by Vishal Surjuse
HTML:
HTML:
<input type="text" class="maskedExt" maskedFormat="3,2" />
maskedFormat="number count before decimal point, number count after decimal point"
Script:
脚本:
$(document).ready(function () {
$('body').on('keyup', '.maskedExt', function () {
var num = $(this).attr("maskedFormat").toString().split(',');
var regex = new RegExp("^\d{0," + num[0] + "}(\.\d{0," + num[1] + "})?$");
if (!regex.test(this.value)) {
this.value = this.value.substring(0, this.value.length - 1);
}
});
});
回答by Mr_Green
I was just testing using regex to learn it. But I recommend going with roasted's solution.
我只是在测试使用正则表达式来学习它。但我建议使用烤的解决方案。
<input id="txtId" type="text"></input>
var txt = document.getElementById('txtId');
txt.addEventListener('keyup', myFunc);
function myFunc(e) {
var val = this.value;
var re = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)$/g;
var re1 = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)/g;
if (re.test(val)) {
//do something here
} else {
val = re1.exec(val);
if (val) {
this.value = val[0];
} else {
this.value = "";
}
}
}
回答by Devraj Gadhavi
Another working solution
另一个工作解决方案
Html
html
<input type="text" id="myTextBox" class="two-decimals">
jQuery
jQuery
$(".two-decimals").on("keypress", function (evt) {
var $txtBox = $(this);
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46)
return false;
else {
var len = $txtBox.val().length;
var index = $txtBox.val().indexOf('.');
if (index > 0 && charCode == 46) {
return false;
}
if (index > 0) {
var charAfterdot = (len + 1) - index;
if (charAfterdot > 3) {
return false;
}
}
}
return $txtBox; //for chaining
});
回答by Snehal Chavan
function checkDecimal(el){
var ex = /^[0-9]+\.?[0-9]*$/;
if(ex.test(el.value)==false){
el.value = el.value.substring(0,el.value.length - 1);
}
}