1

I want to put text into a textarea input element using key events in jquery. I know that it can be simply done with .val() or .html() functions but there's a reason that I want to put text using keyevents. The following is my code:

<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<p>In this example, the text field gets focus immediately after the document window has been loaded.</p>

<textarea id="myText"> </textarea>

<script>

$(function() {
  document.getElementById("myText").focus();
   $('#myText').focus().trigger({ type : 'keypress', which : 65 });
   $('#myText').trigger(jQuery.Event('keypress', { keyCode: 65 })); 

});


</script>

</body>
</html>

I have googled it and realized that there is two different ways of triggering events using jquery. I tried both but neither of which seem to be working.

Vickel
  • 7,879
  • 6
  • 35
  • 56
Wildhammer
  • 2,017
  • 1
  • 27
  • 33

2 Answers2

0

It looks like your keypress event is getting fired, but since it is only an event I don't believe it is actually going to input your value into the field. If you're expecting something to happen on the keypress event from some other code you have, then there is some other issue.

If you demo with this fiddle you'll see the keypress event firing.

Try the code below to change the value of the input field with the new keypress value:

$(function() {
   $('#myText').trigger(jQuery.Event('keypress', { keyCode: 65 })).val($("#myText")
   .val() + String.fromCharCode(65));
});
forrestmid
  • 1,494
  • 17
  • 25
0

The question is answered over there. Being short - key events won't change the actual input due to security reasons, but there is a plugin called "The $.fn.sendkeys Plugin" which can help you with a workaround.

Community
  • 1
  • 1
Mike
  • 1,979
  • 2
  • 16
  • 29