0

I am trying to write a script for Tampermonkey that will insert in a Text input the text from a selected item in a dropdown menu and simulate the Enter key being pressed so the event assigned to that input will be triggered.

This is how I defined my test input,

<input type="text" placeholder="Topics" id="TText" onkeydown="checkEnter(event)">

This is the function that appends the input text to a paragraph, sTopics, when Enter is pressed, for testing purpose

function checkEnter(event) {
  var sTopics;
  var eKey = event.key;
  if (eKey == "Enter") {
    sTopics = document.getElementById("selTopics");
    sTopics.innerHTML += document.getElementById("TText").value.concat("<br>");
    document.getElementById("TText").value = "";
  }
}

And this is the function triggered when an item is selected from the dropdown menu,

function setTopic(newTopic) {
  const ke = new KeyboardEvent('keydown', {
    bubbles: true, cancelable: true, keyCode: 13
  });
  document.getElementById("TText").value = newTopic;
  document.getElementById("myDropdown").classList.toggle("show");
  document.getElementById("TText").dispatchEvent(ke);
}

I've got the KeyboardEvent solution from here but, when I select an item from the D-D, all that happens is that the text gets added to the input, the Enter key is not "detected" (the text doesn't get added to the paragraph and the Input text doesn't get cleared.

Any idea what am I doing wrong and how can I fix it?

Many thanks in advance! :)

  • Add `,key: 'Enter'` after `keyCode:13` – wOxxOm Nov 16 '20 at 07:18
  • @wOxxOm, spot on!! :D Thanks a mill!!! I thought the keyCode would do it. I understand now what the problem was: whereas the listener was waiting for the key "Enter" to arrive, I was sending a keyCode "13". I got the KeyboardEvent event and definition and dispatch from an example and I thought it would be/represent the same, but they are not "exactly", I needed to specify the same attribute on both places. – Pablo Ortiz Nov 16 '20 at 16:58

0 Answers0