Using JavaScript I need to fill an input element by triggering some events instead of setting value attribute of the element. What would be the best way to mock the key press events so that we can fill the input element as if the user is actually typing the characters?
Asked
Active
Viewed 795 times
1

Brian Tompsett - 汤莱恩
- 5,753
- 72
- 57
- 129

Chanikya Mohan
- 47
- 6
-
what is your real use case, you need to solve in which you `can't set the attribute of the element`? – Raghav Garg Sep 17 '18 at 21:27
-
I have a plugin which tries to search for username/password field on a login page and fill it's contents and click submit entirely through JavaScript. There is this one website on which I am able to update the values of input[type="email"] and input[type="password"]. After that, I am triggering the "input" event and "change" event. On chrome and Firefox, this is working normally and submitting the form, but on IE 11 the form element values are being reset before submitting. – Chanikya Mohan Sep 17 '18 at 21:32
-
I tried may methods, but nothing is working. So thought to stimulate the key press of every character instead of just updating value of the element. – Chanikya Mohan Sep 17 '18 at 21:33
-
When I assign a value to the input using element.value="
" on console and then focus of the element or blur it the value is being reset to empty. – Chanikya Mohan Sep 17 '18 at 21:34 -
I hope these could help you https://stackoverflow.com/questions/3368578/trigger-a-keypress-keydown-keyup-event-in-js-jquery, https://stackoverflow.com/questions/596481/is-it-possible-to-simulate-key-press-events-programmatically – Raghav Garg Sep 17 '18 at 21:39
-
@RaghavGarg, I tried all the solutions mentioned there before, it is triggering an key press event but not updating the value of input. – Chanikya Mohan Sep 17 '18 at 21:41
-
Please share the code incase it is not working.! Have you tried focusing the input field before trigger the event? – Raghav Garg Sep 17 '18 at 21:43
-
Yes, I tried focusing the element before updating value - no difference. Unfortunately, I cant share the code. But I am trying to send the UI mock of what I did. I will update it here. – Chanikya Mohan Sep 17 '18 at 21:49
-
`window.setTimeout(function(){ var elem = document.querySelector('input[name="email"]'); elem.focus(); elem.value="abcd@gmail.com"; },2000);` timeout is to click on the webpage after enter on console to trigger the focus and fill the value. – Chanikya Mohan Sep 17 '18 at 22:01
-
You can see that the value is being reset after the element's focus is removed by clicking else where on website. I know that some script from the website is checking for proper email and password and resetting the values if any errors in them. I cant change anything on their website so I need some work around to fill in the values and override the onblur reset value functionality. – Chanikya Mohan Sep 17 '18 at 22:04