Take this HTML code, if you place your cursor on the 1st text-box, and then press Tab Key. The cursor will automatically jump to the 2nd text-box.
Box1:
<textarea id='box' cols='60' rows='10'></textarea>
Box2:
<textarea id='box' cols='60' rows='10'></textarea>
I need to replace this default action of switching to the next textbox with execution of JavaScript function I've defined. Let's say: instead of switching textboxes execute function that writes 'a' on the the 1st text-box upon pressing Tab inside the box.
Any idea how I can make this happen?
CodePudding user response:
You would need to listen to the keydown
event (tested the others they do not work for this specific case). From there you need to check if tab was pressed. Then you would need to prevent the default from happening and finally execute your custom logic. In the example down below the default functionality of tab is only then overwritten if the first textarea is focussed.
<textarea id="box1"></textarea>
<textarea id="box2"></textarea>
document.getElementById("box1").addEventListener("keydown", (event) => {
if (event.keyCode === 9) {
event.preventDefault();
event.target.value = "a"; // adding a to textarea (your example)
}
})