Javascript 只允许输入浮点数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10150877/
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
allowing input only for float number
提问by moc4yu
I have pain-time when making input that only allows float number with jquery library. my code can't prevent chacacter "." when it's becoming first input, can anyone guide me to solve this problem?
在使用 jquery 库进行仅允许浮点数的输入时,我很痛苦。我的代码无法阻止字符“。” 当它成为第一个输入时,有人可以指导我解决这个问题吗?
$('.filterme').keypress(function(eve) {
if ( ( eve.which != 46 || $(this).val().indexOf('.') != -1 )
&& ( eve.which < 48 || eve.which > 57 )
|| ( $(this).val().indexOf('.') == 0)
)
{
eve.preventDefault();
}
});?
采纳答案by Tina CG Hoehr
I filter the first position input with the jQuery Caret plugin. Otherwise, once the dot is typed, it's already late to check where it was placed. I tried checking for the dot, then deleting the dot, but it does not look nice.
我使用 jQuery Caret 插件过滤第一个位置输入。否则,一旦输入点,检查它的位置已经晚了。我尝试检查点,然后删除点,但它看起来不太好。
jQuery caret plugin: http://examplet.buss.hk/js/jquery.caret.min.js
jQuery 插入符插件:http: //examplet.buss.hk/js/jquery.caret.min.js
What I did:
我做了什么:
http://jsfiddle.net/FCWrE/422/
http://jsfiddle.net/FCWrE/422/
Try it :)
尝试一下 :)
$('.filterme').keypress(function(eve) {
if ((eve.which != 46 || $(this).val().indexOf('.') != -1) && (eve.which < 48 || eve.which > 57) || (eve.which == 46 && $(this).caret().start == 0)) {
eve.preventDefault();
}
// this part is when left part of number is deleted and leaves a . in the leftmost position. For example, 33.25, then 33 is deleted
$('.filterme').keyup(function(eve) {
if ($(this).val().indexOf('.') == 0) {
$(this).val($(this).val().substring(1));
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/caret/1.0.0/jquery.caret.min.js"></script>
<input type="text" class="filterme">
回答by billynoah
I use this - works for keyboard input or copy and paste
我使用这个 - 适用于键盘输入或复制和粘贴
$('input.float').on('input', function() {
this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<input type="text" class="float" />
Explanation:
解释:
- First regex replaces anything that's not a number or a decimal.
- Second regex removes any instance of a second decimal.
- 第一个正则表达式替换任何不是数字或小数的东西。
- 第二个正则表达式删除第二个小数的任何实例。
回答by Rodney
Regular expression would be my recommendation as well. If the value is being passed as a number and not a string you can use .toString to change it to a string and validate it with regular expression. For example:
正则表达式也是我的推荐。如果该值作为数字而不是字符串传递,您可以使用 .toString 将其更改为字符串并使用正则表达式进行验证。例如:
var str = value.toString();
if(!str.match(/^-?[0-9]*[.][0-9]+$/)) {
alert("Value must be a float number");
return;
}
return value;
The above regex will match if the value passed is a floating point number. It accepts both negative and positive numbers. If you only want to accept positive numbers simply remove the '-?' from the expression. It will also fail if the value is simply zero '0' without any decimal point. If you want to accept zero simply add it as a condition to the 'if' statement.
如果传递的值是浮点数,则上述正则表达式将匹配。它接受负数和正数。如果您只想接受正数,只需删除“-?” 从表达式。如果该值只是零“0”而没有任何小数点,它也会失败。如果您想接受零,只需将其作为条件添加到“if”语句中。
You can use the above validation and an onchange event to prevent the user from entering a non-flot number.
您可以使用上述验证和 onchange 事件来防止用户输入非飞行号码。
回答by Rami Shareef
Why not using Regular Expression
为什么不使用 Regular Expression
^[0-9]*[.][0-9]+$
回答by Deepak Jha
You can use the following method, called on onkeypressevent. Below is the HTML snippet followed by the JS method:
您可以使用以下方法,在onkeypress事件上调用。下面是 HTML 代码片段,然后是 JS 方法:
input type="text" onkeypress="return isNumberKey(event)" id="floor"
input type="text" onkeypress="return isNumberKey(event)" id="floor"
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode == 46){
var inputValue = $("#floor").val();
var count = (inputValue.match(/'.'/g) || []).length;
if(count<1){
if (inputValue.indexOf('.') < 1){
return true;
}
return false;
}else{
return false;
}
}
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)){
return false;
}
return true;
}
Note: The above code also ensures that you enter only single decimal in the input.
注意:上面的代码还确保您在输入中只输入一个小数。
回答by Jhon Didier Sotto
This works for me:
这对我有用:
var str = document.getElementById('product_'+id_product).value;
if( !str.match(/^[0-9]*([.,][0-9]+)?$/) ) {
console.log("Value must be a number or float number");
}else{
console.log("The number is valid");
}
I hope this can help someone. Regards!
我希望这可以帮助某人。问候!
回答by dino
Here is my solution, works with negative numbers too (fiddle)
这是我的解决方案,也适用于负数(小提琴)
$("input").keypress(function (event) {
var inputCode = event.which;
var currentValue = $(this).val();
if (inputCode > 0 && (inputCode < 48 || inputCode > 57)) {
if (inputCode == 46) {
if (getCursorPosition(this) == 0 && currentValue.charAt(0) == '-') return false;
if (currentValue.match(/[.]/)) return false;
}
else if (inputCode == 45) {
if (currentValue.charAt(0) == '-') return false;
if (getCursorPosition(this) != 0) return false;
}
else if (inputCode == 8) return true;
else return false;
}
else if (inputCode > 0 && (inputCode >= 48 && inputCode <= 57)) {
if (currentValue.charAt(0) == '-' && getCursorPosition(this) == 0) return false;
}
});
function getCursorPosition(element) {
if (element.selectionStart) return element.selectionStart;
else if (document.selection)
{
element.focus();
var r = document.selection.createRange();
if (r == null) return 0;
var re = element.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
}