Reputation: 237
I have a numeric textbox, by default numeric textbox allows Exponents and periods. How do i restrict that?
One of the method i can think of is using string.replace on input event however it is not working as expected. Below is my code..
HTML
<input type='number' class='number'>
JavaScript
$(".number").on('input', function () {
this.value = this.value.replace(/e|E|\./g, ''); // Remove e, E, and period(.)
if (this.value.length > 4) {
this.value = this.value.slice(0, 4);
}
});
When i enter string '2e' in textbox, entire input is getting removed if above code is ran. i just wants to remove e, E or period from input string not entire input.
Is there a way to achieve this.
Answer BY nichel is working like a charm, now my problem is how do i restrict the same in PASTE event.?
Upvotes: 0
Views: 1151
Reputation: 18995
So basically you want to allow just numbers? Then restrict the keys by keycode & remove excess chars on paste
$(".number").keypress(function(e){
return e.keyCode>47&&e.keyCode<58;
}).paste(function(){
$(this).val($(this).val().replace(/\D/g,''));
})
And since you'd like the max length to be 4, just add max="9999"
:
<input type='number' class='number' max="9999">
Upvotes: 0
Reputation: 24925
input[type=number]
returns ""
(blank string) if input value is not valid.
You can refer this post for more information.
I would suggest you to use input[type=tel]
instead. It also has a maxLength
attribute so you so not have to worry about trimming extra values.
You can even replace your regex to /[^0-9]/
. This will replace all characters except numbers.
So you final code would look like: JSFiddle
Upvotes: 0