Jared Smith's comment above provides the following solution:
onButtonClick() {
const input = document.querySelector('inputSelector'); // or you can possibly use a ref here
const e = document.createEvent('HTMLEvents');
e.initEvent("keypress", false, true);
e.keyCode = 13; // I believe 13 is the enter key
input .dispatchEvent(e);
}
[edit] apparently initEvent
is now deprecated in favor of new Event
. see here: https://developer.mozilla.org/en-US/docs/Web/API/Event/Event
[edit2] I made a jsfiddle to show how new Event
would work:
https://jsfiddle.net/pnwj97qs/
const $input = document.querySelector('input');
$input.addEventListener('keypress', function(e){
if (e.key === 'Enter') {
const value = e.target.value;
document.querySelector('.result').textContent = value + ' was entered';
}
})
const $button = document.querySelector('button');
$button.addEventListener('click', function() {
var e = new Event('keypress');
e.key = 'Enter';
e.keyCode = 13;
$input.dispatchEvent(e);
})
<button>simulate enter key</button>
<input type="text">
<div class="result"></div>
As you can see, I tie the behavior to the "Enter" key, and it works even when you press the button because of the dispatch
event.