Reputation: 35
I have function in JS which works fine with commas. I need to make it work with dot (ie. a number with a dot, not a comma). How can I change it? Replace in indexOf(',')
to indexOf('.')
has not helped me.
$(".isInputNumber").on("keypress keyup blur", function(event) {
var $this = $(this);
if ((event.which != 44 || $this.val().indexOf(',') != -1)
&& ((event.which < 48 || event.which > 57)
&& (event.which != 0 && event.which != 8))) {
event.preventDefault();
}
var text = $(this).val();
if ((event.which == 44) && (text.indexOf(',') == -1)) {
setTimeout(function() {
if ($this.val().substring($this.val().indexOf(',')).length > 3) {
$this.val($this.val().substring(0, $this.val().indexOf(',') + 3));
}
}, 1);
}
if ((text.indexOf(',') != -1)
&& (text.substring(text.indexOf(',')).length > 2)
&& (event.which != 0 && event.which != 8)
&& ($(this)[0].selectionStart >= text.length - 2)) {
event.preventDefault();
}
});
Upvotes: 1
Views: 143
Reputation: 51
Use search
method, bacause it accepts regexp as an argument. And it will find first dot/comma.
In your case it will be like search(/\.|,/)
. You can just replace your indexOf
calls, because search
also return an index of first match.
For example:
"123,123".search(/\.|,/) // return 3
"123.123".search(/\.|,/) // return 3 also
Upvotes: 0
Reputation: 116
The event.which
property indicates the specific key or button that was pressed (44 code represents a comma). You should change that value to a dot code (i.e. 46) in accordance with ASCII
Upvotes: 1