How to insert a value using Event keydown or keypress with Javascript / Jquery

Asked

Viewed 19 times

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 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.

  • but how to simulate? type outside and apply the value inside the input? or type inside the input but not use the property val() or value()

  • That, I don’t want to set the value using methods like val() or value(), I need to pretend that this was typed by the keyboard, as if I had dictated the letter "a" by the keyboard.

  • you can use the jQuery(this).attr('value', KeyboardEvent.key);

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.