0
I would like to know how to insert a word into the value
of a input
using keydown or keypress instead of setting the value by a method.
For example, I don’t want to use a method like: $("#coupon").value = "teste"
. I want to simulate that the "a" key was typed inside the input.
I tried the following javascript code in my HTML to insert the text "a" inside the value
of input
, simulating the keyboard action, but it didn’t work:
let element = document.querySelector('#coupon');
element.dispatchEvent(new KeyboardEvent('keydown',{'key':'a'}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="coupon" type="text" required="required" />
Behold Keyboardevent.key. I suggest edit your question and add more details, attempts and etc, so that it meets the criteria of a [Mre]. Your question is not clear, specify and exemplify in more detail!
– gleisin-dev
@gleisin-dev explained better what I want and my code was based on documentation, posted help here because the code didn’t work and wanted to see if someone with more experience could help make it work.
– Wendell
but how to simulate? type outside and apply the value inside the input? or type inside the input but not use the property
val()
orvalue()
– gleisin-dev
That, I don’t want to set the value using methods like
val()
orvalue()
, I need to pretend that this was typed by the keyboard, as if I had dictated the letter "a" by the keyboard.– Wendell
you can use the
jQuery(this).attr('value', KeyboardEvent.key);
– gleisin-dev