I have a HTML textbox. How to allow only numbers in it on keypress event?
There is a type=number however I have use type text.
-
See this: stackoverflow.com/a/41479077/1791913FAISAL– FAISAL2017-07-31 14:17:03 +00:00Commented Jul 31, 2017 at 14:17
-
why you need text box? if only accepting numbers.Hareesh– Hareesh2017-07-31 14:17:32 +00:00Commented Jul 31, 2017 at 14:17
-
Why do you have to use type text? Who or what is forcing you to?k0pernikus– k0pernikus2017-07-31 14:25:28 +00:00Commented Jul 31, 2017 at 14:25
Add a comment
|
3 Answers
You can use "keypress" event in your text input. You can use this function.
<input id="example" type="text" [(ngModel)]="example" (keypress)="OnlyNumbers($event)" />
public OnlyNumbers($event) {
let regex: RegExp = new RegExp(/^[0-9]{1,}$/g);
let specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home', 'ArrowRight','ArrowLeft'];enter code here
if (specialKeys.indexOf($event.key) !== -1) {
return;
} else {
if (regex.test($event.key)) {
return true;
} else {
return false;
}
}
}
2 Comments
Can Karakoyun
Yeah it's works but you can prefer the directives for this issue.
Nyerguds
Why is there a normal "return" in what should be a boolean function? What does that return?
You can use Reactive Forms in your component and for allowing only numbers in input field you can use Validators.pattern("^\\d+$") like minlength, required validations are handled in this form.
Comments
HTML:
<input type="text" (input)="onTextboxChangeValidate($event)">
TS file include below function
onTextboxChangeValidate(event: Event)
{
var inputData = (<HTMLInputElement>event.target).value;
//replace more than one dot
var extractedFte = inputData.replace(/[^0-9.]/g, '').replace('.', '')
.replace(/\./g, '').replace('x', '.');
//Extract nuber Values
extractedFte = extractedFte.replace(/^(\d+)\d*$/, "$1");
//Reasign to same control
(<HTMLInputElement>event.target).value = extractedFte;
}
3 Comments
Hille
Welcome to SO! Please explain what your code does, otherwise user with the same problem wount be able to learn of your solution.
ArulKumar Sivaraj
Actually i wrote function for restrict 2-decimal values from that i derived above one. We can use same function for allow decimal values for slight modification. See below two examples u can understand. for allow only 2 decimal value - arulkumarsivaraj.blogspot.com/2020/06/… Allow only numbers: arulkumarsivaraj.blogspot.com/2020/06/…
ArulKumar Sivaraj
Actually written regx for allow one dot, for only number no need that so replaced with empty. //replace more than one dot inputData.replace(/[^0-9.]/g, '').replace('.', 'x') -> it will extract numbers and dots from that we replace first dot with x. .replace(/\./g, '') -> it will remove other dots .replace('x', '.') -> again replace x to Dot