3

I need to add some chars to input only by events, without access to input.value. My try:

HTML:

<input id="text" type="text">

JS:

// prepare     
let et = document.getElementById('text');
et.value = '';

// my try
et.dispatchEvent(new KeyboardEvent('keydown',  {key:'s', code:'KeyS', bubbles: true})); 
et.dispatchEvent(new KeyboardEvent('keypress', {key:'s', code:'KeyS', bubbles: true}));
et.dispatchEvent(new InputEvent('input', {}));
et.dispatchEvent(new KeyboardEvent('keyup', {key:'s', code:'KeyS', bubbles: true}));

// check
if (et.value === 's')
    alert ('success');
else 
    alert ('failure');

I have got 'failure' always. I need 'success')

M.Onyshchuk
  • 165
  • 9
  • You need to listen for the events before emitting them. `et.addEventListener('keypress', (e) => et.value += e.key); ` – pilchard Dec 18 '21 at 21:23
  • 1
    Does this answer your question? [Chrome: Simulate keypress events on input text field using javascript](https://stackoverflow.com/questions/50219800/chrome-simulate-keypress-events-on-input-text-field-using-javascript) – zero298 Dec 18 '21 at 22:08
  • I can`t fill input by value like et.value = 's'. I have access to input.value only for setup or check. – M.Onyshchuk Dec 18 '21 at 22:16
  • "For example, manually firing a key event does not cause that letter to appear in a focused text input." - Thank you! It`s an partial answer to my question. – M.Onyshchuk Dec 18 '21 at 22:20
  • As in the linked duplicate, an input will not fill due to manual firing of events. That will only trigger your attached listeners, not default behaviors. – zero298 Dec 18 '21 at 23:26

0 Answers0