1

I'm trying to autofill and trigger the 'Enter' keydown event on a textarea overdid by React.

The input autofill was resolved by this answer, thanks a lot to the author : https://stackoverflow.com/a/46012210/7260325

The only problem left is the 'Enter' key triggering. Standard JS methods available to achieve that seems to not work because of this React override. Anyone have a clue on how I can trigger these event ?

there is the code :

// I target my TextArea
var input_field = document.getElementsByClassName('MyTextArea')[0];

/*
 * Fill Textarea value
 * Tricks the React listener override
 */
var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;
nativeInputValueSetter.call(input_field, 'Toto And His friendssss');

var ev2 = new Event('input', { bubbles: true});
input_field.dispatchEvent(ev2);

// I try to fire the keydown 'Enter key' event
var ev3 = document.createEvent('KeyboardEvent');
// Send key '13' (= enter)
ev3.initKeyEvent(
    'keydown', true, true, window, false, false, false, false, 13, 0);

input_field.dispatchEvent(ev3);

Thank you in advance for your help.

keizo
  • 11
  • 1
  • 5
  • As far as I understand, you simply try to trigger a keypress event with params. It's solved there: https://stackoverflow.com/a/18937620/2054977 – enguerranws Apr 23 '18 at 14:17
  • Might be a duplicate of this - https://stackoverflow.com/questions/27827234/keypress-event-handling-in-reactjs – jolyonruss Apr 23 '18 at 14:44
  • @enguerranws thanks for the link, but unfortunately wasn't able to make it work, It seem's that React is taking over the actions on the textarea field, and all the JS methods are not taken in count due tu that. In the response I added in my question, `var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set; nativeInputValueSetter.call(input, 'react 16 value'); ` those lines soleved the same issue with the input.value dynamic setting. But I don't know how to do the same with the keydown/keypress action. – keizo Apr 23 '18 at 15:08
  • @jolyonruss thanks for the link, but I'm trying to achieve that in JS not React.js – keizo Apr 23 '18 at 15:09
  • @keizo Then, you really should paste some code in your question, it would be easier for us to help you. – enguerranws Apr 23 '18 at 15:09
  • @keizo Can you edit your question to paste this part of code? It's unreadable as a comment. – enguerranws Apr 23 '18 at 15:16
  • @enguerranws updated sorry. – keizo Apr 23 '18 at 15:24

1 Answers1

0

So,
The solution was quite simple, but I mixed up the commands to trigger.
Thx to @enguerranws for link containing the lead.

var ev3 = document.createEvent('KeyboardEvent');
ev3.initKeyEvent(
    'keypress', true, true, window, false, false, false, false, 13, 0);
input_field.dispatchEvent(ev3);
keizo
  • 11
  • 1
  • 5