I'm trying to limit my user input to conform to 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/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.