2

I know similar questions to this have been asked before, but all of the answers I could find are either in jQuery or don't seem to work anymore. I've tried doing variations of

function send(char, elem) {
   let e = new KeyboardEvent('keydown', {key: char});
   elem.dispatchEvent(e);
}

but no luck. The event it dispatched and triggers the appropriate handlers, but the key is not typed if an input/textarea element is focused.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Mason
  • 738
  • 7
  • 18
  • Try this: https://stackoverflow.com/questions/596481/is-it-possible-to-simulate-key-press-events-programmatically – Gaurav Punjabi Jun 15 '19 at 07:15
  • Possible duplicate of [Is it possible to simulate key press events programmatically?](https://stackoverflow.com/questions/596481/is-it-possible-to-simulate-key-press-events-programmatically) – Herohtar Jun 15 '19 at 07:16
  • @GauravPunjabi so is the current answer just "you can't"? – Mason Jun 15 '19 at 15:35

1 Answers1

0

You can't make the typing occur from an event you trigger via the code - you can set up a listener, however, and make a custom event as so not to confuse the triggered event with a regular keypress.

$("#button").on("click", function() {
  $("#input").trigger({
    type: "myKeypress",
    which: "A".charCodeAt(0)
  });
});

$("#input").on("myKeypress", function(e) {
  $(this).val($(this).val() + String.fromCharCode(e.which));
});
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<input type="text" id="input">
<button id="button">Type A</button>

You can make this work with all keys too:

$("#button").on("click", function() {
  $("#input").trigger({
    type: "myKeypress",
    which: prompt("Enter a letter").charCodeAt(0)
  });
});

$("#input").on("myKeypress", function(e) {
  $(this).val($(this).val() + String.fromCharCode(e.which));
});
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<input type="text" id="input">
<button id="button">Type a letter</button>
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79