I need help with triggering a keydown event that changes the pressed key to a comma. If a non-numeric value is entered, it should simulate the comma and write it in the textbox. However, after the second call, the comma is not displayed. Any suggestions on how to fix this issue?
Thank you.
<input type="text" (keydown)="validate($event)" />
validate(event) {
if (!this.validatenumeric(event)) {
event.preventDefault();
} else {
if(event.key!==","){
event.preventDefault();
var getterCode = { get: function () { return 188 } };
var getsourceCapabilities = { get: function () { return event.sourceCapabilities } };
var e = new KeyboardEvent("keydown", {
altKey: false,
bubbles: true,
cancelable: true,
code: "Comma",
composed: true,
ctrlKey: false,
key: ",",
detail: 0,
location: 0,
metaKey: false,
repeat: false,
shiftKey: false,
view: window
});
Object.defineProperties(e, {
which: getterCode,
keyCode: getterCode,
sourceCapabilities: getsourceCapabilities
});
this.elementRef.nativeElement.querySelector('input').dispatchEvent(e);
}
}
}
validatenumeric(key) {
var keycode = (key.which) ? key.which : key.keyCode;
//comparing pressed keycodes
if ((keycode >= 48 && keycode <= 57)) {
// 0-9 only
return true;
} else if ((keycode >= 96 && keycode <= 105)) {
// 0-9 only
return true;
}
else return false;
return false;
}
Update: I may have found a solution by handling keyup events instead of trying another keydown event. By checking for commas, locating the cursor position, and inserting the comma accordingly, I believe this approach could work. Any input or advice would be appreciated!
> <input type="text" (keydown)="validate($event)"
> (keyup)="validateUp($event)" />
>
> validateUp(event) {
> let pos = this.elementRef.nativeElement.querySelector('input').selectionEnd;
> if (event.key == ',' ) {
> this.textValue = text.slice(0, pos) + event.key + text.slice(pos);
> }
> }
>
>
> validateWithtDecimals(event) {
> var text: string = this.textValue;
>
>
> if (!this.validatenumeric(event, text, this.separator)) {
> event.preventDefault();
> }
> else {
>
> if(event.key!==","){
> event.preventDefault();
>
> var getterCode = { get: function () { return 188 } };
>
> var e = new KeyboardEvent("keyup", {
> altKey: false,
> bubbles: true,
> cancelable: true,
> code: "Comma",
> composed: true,
> ctrlKey: false,
> key: ",",
> detail: 0,
> location: 0,
> metaKey: false,
> repeat: false,
> shiftKey: false,
> view: window
> });
>
> Object.defineProperties(e, {
> which: getterCode,
> keyCode: getterCode,
> });
>
> this.elementRef.nativeElement.querySelector('input').dispatchEvent(e);
> }
> }
> }