I am trying to imitate the behaviour of "Enter" key in my Code by using "Tab" key. I tried using "keydown" which gets the console.log printed but doesn't let me enter anything in the input field. Here's my code.
HTML File:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="test.css">
<title>Document</title>
</head>
<body>
<div class="input">
<input id="text-area">
<button id="myBtn" onclick="selectText()" >Select Text</button>
</div>
<script src="test.js"></script>
</body>
</html>
JavaScript file:
let input = document.getElementById('text-area');
let button = document.getElementById('myBtn');
input.addEventListener("keyup",e=>{
e.preventDefault();
if(e.key=='Enter'){
console.log("Enter is pressed");
button.click();
}
});
function selectText(){
let input1 = document.getElementById('text-area');
input1.focus();
input1.select();
}
The TAB key is a special key reserved for navigation between HTML elements. So to use it for anything beside navigation you need to intercept the keydown event for this key and call preventDefault() on it.
For example:
let input = document.getElementById('text-area');
let button = document.getElementById('myBtn');
input.addEventListener("keyup", e => {
if (e.key == 'Tab') {
console.log("Enter/Tab is pressed");
button.click();
}
});
input.addEventListener("keydown", e => {
if (e.key == 'Tab') {
e.preventDefault();
}
});
function selectText() {
let input1 = document.getElementById('text-area');
input1.focus();
input1.select();
}
<div class="input">
<input id="text-area">
<button id="myBtn" onclick="selectText()">Select Text</button>
</div>
Update this answer is only related by Angular, not about javascript
<input (keydown.tab)="selectText()">
And forget create an eventListener keydown.enter.
But answer to your question you can dispathEvent. Some like(*)
<!--see how you create a template reference variable and pass
to the function-->
<input #inputId (keydown.tab)="createEnterEvent(inputId)">
createEnterEvent(el: HTMLInputElement) {
const event = new KeyboardEvent('keydown',{
code: "Enter",
key: "Enter",
keyCode: 13
});
el.dispatchEvent(event);
}
But this not make a "submit" of the form. Only is util if you has an keydown.enter event defined in your input
(*)NOTE about template reference variable. In Angular 13, when you pass as function you has the "HTMLElement", when you get using @ViewChild you get a elementRef and you should use yourVariable.nativeElement to get the htmlElement