Reputation: 193
live: http://jsfiddle.net/2KRHh/3/
$('#price').keyup(function(){
$('#price').val($('#price').val().replace('..', '.'));
})
I would like have only one dot in input. This working, but only for .. digit. If i still hold comma this not working, so i would like replace this with regular expression - if is two or more dot this should replace one more.
This should also remove dot if is in different place - for example
11.23.32 - should remove second dot.
Upvotes: 2
Views: 2561
Reputation: 173562
If you want to leave the first period alone and remove the others, the expression is simple:
/\./g
It basically matches all periods; so how are we making sure to only match the second, third, etc.? Simple, you manage that in a replacement function:
var $price = $('#price'),
new_str = function(str) {
var i = 0;
return str.replace(/\./g, function() {
return ++i >= 2 ? '' : '.';
});
}($price.val());
$price.val(new_str);
The variable i
is used to keep track of how many times the period has been matched; if it has matched two times or more, it returns an empty string and effectively removes the period.
Upvotes: 2
Reputation: 324640
You should NEVER restrict the user from what they want to type. When validating, you should show some kind of warning or auto-correct it AFTER they are done typing.
Therefore, try this:
<input type="number" min="0" step="0.01" />
Because, amazingly, browsers are bloody powerful systems that don't have to be spoon-fed everything ;)
However, if compatibility is a major concern (note: it shouldn't be, because you should never trust client input anyway and always validate on the server), try this:
<input type="number" min="0" step="0.01"
onChange="this.value=Math.max(0,Math.floor((parseFloat(this.value)||0)*100)/100);" />
Upvotes: 0
Reputation: 29399
And to give you another choice.....
$('#price').keyup(function(){
$('#price').val($('#price').val().replace(/([^.]*\.[^.]*)\./,'$1'));
})
Upvotes: 0
Reputation: 33163
Change the event to keydown and stop the event if the keypress is a dot and there is already at least one dot in the value.
$('#price').keydown( function(e) {
if( e.which === 190 && $(this).val().indexOf( '.' ) !== -1 ) {
return false;
}
});
Demo: http://jsfiddle.net/2KRHh/9/
Upvotes: 0
Reputation: 613
I don't know if regular expressions are the best way to go about this.
Or the relevant code:
var str = $('#old').val();
var dot = str.indexOf('.');
var newstr = str.substring(0, dot) + '.' + str.substring(dot).replace('.', '', 'g');
console.log(str, newstr);
$('#new').val(newstr);
The code finds the first dot and saves its position, then replaces the rest of the dots with empty string.
Upvotes: -1