[英]I'm trying to limt user input to a valid price using jquery & javascript. How do i prevent second decimal point
I'm trying to limit my user input to conform to 999.99 我试图限制用户输入以符合999.99
I am using this code to try and exclude the entry of a second decimal point but it doesn't work. 我正在使用此代码尝试排除第二个小数点的输入,但它不起作用。 Can anyone help me out on this ?
有人可以帮我吗?
jQuery(".textr2").live('input', function (event) {
var str = jQuery(this).val();
alert(str);
if (str.search('.')) {
alert("Finds a dot");
jQuery(this).val(jQuery(this).val().replace(/[^0-9]/g, ''));
}
else {
alert("NO Dot");
jQuery(this).val(jQuery(this).val().replace(/[^0-9\.]/g, ''));
});
You could try checking the value enter on keypress. 您可以尝试检查按键上输入的值。
Try 尝试
$("#test1").keypress(function(event)
{
var numberPattern = /^([0-9]{0,3})(\.[0-9]{0,2})?$/;
var key = event.which;
var character = String.fromCharCode(key);
var selectionStart = this.selectionStart;
var value = $(this).val();
var stringPattren = new RegExp('(.{'+selectionStart+'})');
var replacePattren = '$1'+character;
var string = value.replace(stringPattren,replacePattren);
var isTab = key === 0;
var isBackspace = key === 8;
var shouldTest = ! isBackspace && ! isTab;
var passed = ! shouldTest;
if(shouldTest)
{
passed = numberPattern.test(string);
}
return passed;
});
var str = this.value;
var firstDot = str.indexOf('.');
var secondDot = str.indexOf('.', firstDot + 1);
if ( firstDot >= 0 && secondDot >= 0 ) {
this.value = str.substr(0, secondDot) + str.substr(secondDot + 1);
}
Here's the fiddle: http://jsfiddle.net/YN4ta/ 这是小提琴: http : //jsfiddle.net/YN4ta/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.