0

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);
          }

0

4 Answers 4

1

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
'[email protected]'.split('').forEach(letter => {
  typeInto(el, letter)
})
<input type="email" class="js-login-email"/>

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much! That is exactly what I was after! I was also a little confused about the .initKeyboardEvent() as it was different for chrome and firefox and now when it was deprecated also that made sense :) I can't thank you enough!!! Thank you!
So glad it was helpful :)
0

Mb you try addEventListener?

elem.AddEventListener("keypress", (e) => {

    var e = document.createEvent('KeyboardEvent');

    if(e.keyCode === 65) {
        //...
    }

    document.getElementById('login-email').dispatchEvent(e);

});

4 Comments

I dont know how that works. I dont know if I need to combine my code with your code. I am little lost when it comes to the logic here? The above code "listens" for a keypress, but the keypress doesn't work in my first post?
@Andreas This code listen your keypress , and if code of this keypress is 65("A"), running your function . Sorry , my english so low
I am not sure I understand. I posted an answer where I try to combine my code with yours but I cant understand how to do it?
It should be elem.addEventListener, instead of elem.AddEventListener.
0

you can make it by makeing keydown event then you can get your button keycode

like this

window.addEventListener("keydown", function (event) {
  console.log(event.keyCode)
});

so in your code it will be like this


window.addEventListener("keydown", function (event) {

  if(event.keyCode === 65){
     console.log('hello, world');
  }
}, true);

if you don't know which keycode you need to check this website will give you the code for each key

or if you want do it from your key name you can make it like this

window.addEventListener("keydown", function (event) {

  console.log(event.key)
});

NOTE: the key code for each button is come from assci code if you don't know what is it you can check this link

5 Comments

Thanks, but doesn't an eventlistener just "listens" for a keydown? or do I not understand. Shouldn't I keypress something in the first place like in my first post?
you should add eventlistener to check every time this event fires
I am not sure that I need the evenlistener? The problem is to programatically put the letter "A" into the 'login-email' input box. I will not type anything on the keyboard.
do you want only add A letter in your input value after your page loads ?
I will later put an email letter by letter like: [email protected] on page load(So i will then put the letters with a loop). But the important thing is to simulate keypress and not just put it as a .value since the input box requires to actually type it down.
0

I have tried to combine the code now but are not sure if I do this right.

Please notice that I want to programatically press the letter "A" into the 'login-email' box by running the presskey() function. I tried to run the below code but only the alert box is shown?

              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);
              }


var elem = document.getElementById('login-email');
elem.AddEventListener("keypress", (e) => {

    var e = document.createEvent('KeyboardEvent');
    if(e.keyCode === 65) {
        //...
    }
    document.getElementById('login-email').dispatchEvent(e);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.