I am trying to and have to keypress
the letter 'A' with JavaScript.
In the code below, there is an alert('hello')
box that indicates that the code is executing.
But this code doesn't set any values to the "login-email" input (which is a textbox).
What can be wrong with the code?
function presskey()
{
var e = document.createEvent('KeyboardEvent');
if (e.initKeyboardEvent)
{
alert('hello'); e.initKeyboardEvent('keypress', true, true, document.defaultView, 'A', 0, '', false, '');
}
document.getElementById('login-email').dispatchEvent(e);
}
First, I'd like to note that .initKeyboardEvent()
is deprecated. What you likely want is the event constructor (Ex. for an 'input' event, new InputEvent()
, as seen in the code below)
That said, the rest of my answer assumes the question should actually be "How do I manually trigger input events on a textbox?". Please let me know if this isn't actually what you want, but the same concepts should apply to other types of events.
...if this is your actual question, I can show you how I would start solving this problem:
const typeInto = (el, data) => {
// Note the use of the InputEvent constructor
const e = new InputEvent('input', {
inputType: 'insertText',
data,
})
// Manually add the text to element.value
el.value += data
// Fire the event like you were doing
el.dispatchEvent(e)
}
// Get element
const el = document.querySelector('.js-login-email')
// Add an event listener for the 'input' event, to prove it's working
el.addEventListener('input', e => {
console.log(`${e.inputType}: ${e.data}`)
})
// Example "typeInto" usage: call for each letter in the string below
'example@example.com'.split('').forEach(letter => {
typeInto(el, letter)
})
<input type="email" class="js-login-email"/>