Trigger a keypress/keydown/keyup event in JS/jQuery?

后端 未结 9 2069
长情又很酷
长情又很酷 2020-11-22 07:10

What is the best way to simulate a user entering text in a text input box in JS and/or jQuery?

I don\'t want to actually put text in the input box,

9条回答
  •  不思量自难忘°
    2020-11-22 07:31

    You can achieve this with: EventTarget.dispatchEvent(event) and by passing in a new KeyboardEvent as the event.

    For example: element.dispatchEvent(new KeyboardEvent('keypress', {'key': 'a'}))

    Working example:

    // get the element in question
    const input = document.getElementsByTagName("input")[0];
    
    // focus on the input element
    input.focus();
    
    // add event listeners to the input element
    input.addEventListener('keypress', (event) => {
      console.log("You have pressed key: ", event.key);
    });
    
    input.addEventListener('keydown', (event) => {
      console.log(`key: ${event.key} has been pressed down`);
    });
    
    input.addEventListener('keyup', (event) => {
      console.log(`key: ${event.key} has been released`);
    });
    
    // dispatch keyboard events
    input.dispatchEvent(new KeyboardEvent('keypress',  {'key':'h'}));
    input.dispatchEvent(new KeyboardEvent('keydown',  {'key':'e'}));
    input.dispatchEvent(new KeyboardEvent('keyup', {'key':'y'}));

    MDN dispatchEvent

    MDN KeyboardEvent

提交回复
热议问题