0

I want to generate a virtual keyboardEvent(tab). I did some research on the same and got few usefully answers, however it not working for me. I understand that Javascript is event driven programming language so User should press require key, but I also want to understand that can we generate an keyboard event through JavaScript.

function fnGenerateTabKeyEvent() {
    var e = document.createEventObject("KeyboardEvent");
    e.keyCode = 9; // tab's ASCII
    document.getElementsByName("someTxtBox").fireEvent("onkeyup", e);
}
<input type="text" id="someTxtBox"/>

It's not working in IE8 and I'm not getting any error either. I just want that whenever I can this function it should an keyboardevent(tab) from that text box.

Source1,Source2. Any suggestion will be helpful.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
SK.
  • 4,174
  • 4
  • 30
  • 48

1 Answers1

1

I think you were too hasty, as your code works on my machine:

<html>
<body>
<input type="text" id="someTxtBox" onkeyup="window.alert(event.keyCode)"/>
<script type='text/javascript'>
function fnGenerateTabKeyEvent() {
    var e = document.createEventObject("KeyboardEvent");
    e.keyCode = 9; // tab's ASCII
    document.getElementById("someTxtBox").fireEvent("onkeyup", e);
}

fnGenerateTabKeyEvent();
</script>
</body>
</html>

There're of course some "issues" (like - accessing elements via getElementsByName, maybe having the script called before the <input>, but let's blame that on copy-pasting ;)) As such, on my IE, running in document mode 8 the alert successfully displays 9.

eithed
  • 3,933
  • 6
  • 40
  • 60
  • From IE9 forward and for all other browsers you use createEvent() and dispatchEvent() rather than createEventObject and fireEvent(). The leading 'on' in the event name is also dropped. See http://stackoverflow.com/a/2490876/921640 – ClearCrescendo May 14 '15 at 10:26
  • @ClearCrescendo None of these methods appears to work at all with keyboard events! – Michael May 01 '18 at 03:52