javascript 使用javascript或jquery只允许2个小数点输入到文本框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16666415/
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 javascript or jquery?
提问by user2156088
I called a class called test for my textbox. When I entered the first value for e.g. the first value as 4.
, then suddenly the output coming as 4.00
. I just want to restrict entry only for two decimal places.
我为我的文本框调用了一个名为 test 的类。当我输入第一个值时,例如第一个值 as 4.
,然后突然输出为4.00
. 我只想限制输入小数点后两位。
$(".test").keyup(function (event) {
debugger;
this.value = parseFloat(this.value).toFixed(2);
});
回答by HBP
This small change to your code may suffice:
对代码的这个小改动可能就足够了:
this.value = this.value.replace (/(\.\d\d)\d+|([\d.]*)[^\d.]/, '');
Essentially replace the decimal point followed by any number of digits by a decimal point and the first two digits only. Or if a non digit is entered removes it.
基本上用小数点和前两位数字替换小数点后跟任意数量的数字。或者,如果输入了非数字,则将其删除。
回答by RobG
You shouldn't worry about what the user has in the input until they submit the form. You really don't care what's in there before then. However, if you want to warn about invalid input, you can put a message on the screen if you detect non–conforming input, e.g.
在用户提交表单之前,您不必担心用户输入的内容。在那之前你真的不在乎那里有什么。但是,如果您想警告无效输入,则可以在检测到不符合要求的输入时在屏幕上显示一条消息,例如
<script>
function validate(element) {
var re = /^\s*\d*\.?\d{0,2}\s*$/;
var errMsg = "Number must have a maximum of 2 decimal places";
var errNode = document.getElementById(element.name + '-error')
if (errNode) {
errNode.innerHTML = re.test(element.value)? '' : errMsg;
}
}
</script>
You should probably also put a listener on the change handler too to account for values that get there by other means.
您可能还应该在更改处理程序上放置一个侦听器,以解释通过其他方式到达那里的值。
回答by vino20
$(document).on("keyup", ".ctc", function ()
{
if (!this.value.match(/^\s*\d*\.?\d{0,2}\s*$/) && this.value != "") {
this.value = "";
this.focus();
alert("Please Enter only alphabets in text");
}
});
回答by Aioros
回答by Anoop Joshi
you can use the maxLength attribute for that, try
您可以为此使用 maxLength 属性,请尝试
$(".test").keyup(function (event) {
var last = $(this).val()[$(this).val().length - 1];
if (last == '.') {
$(".test").attr("maxlength", $(this).val().length+2);
}
});