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! :)