-2

I don't want to set text in <textarea> with $('textarea').val('text'), I want to set it with events.

HTML

<textarea>

Event Listerner

$("textarea").on("keyup keydown keypress", function(e) {
  console.log("Event: %s", this.type, e.which);
});

Manually typing "1" in textarea

Result: "1" display in textarea and events are

Event: keydown 49
Event: keypress 49
Event: keyup 49

Now trying to enter "1" in textarea with jQuery

var e0 = jQuery.Event("keydown");  e0.which = 49;
var e1 = jQuery.Event("keypress"); e1.which = 49;
var e2 = jQuery.Event("keyup");    e2.which = 49;

$('textarea').trigger(e0).trigger(e1).trigger(e2);

Output: all events occur but "1" does not display in textarea.

Event: keydown 49
Event: keypress 49
Event: keyup 49
  • How can I display or set text in textarea with keyevents?
  • when keyevents trigger then why "1" does not display in textarea?

Example JS fiddle https://jsfiddle.net/np1h9c8k/3/

Asad Raza
  • 34
  • 1
  • 2
  • 14

1 Answers1

0

Your code works fine and does exactly as it should. You're only triggering events, simulating keypress, keydown, keyup. Those events are bound one-way, they only receive the event from the element, they don't transmit an event back to the element, and thank goodness for that.

If they did, then every time someone listened for one of these events, whatever they typed would get multiplied in the input, like this mocked up snippet

$("textarea").on("keyup keydown keypress", function(e) {
  // this is the action you're expecting
  $(this).val(function() {
    return this.value + String.fromCharCode(e.which);
  })
});

function abc() {
  var e0 = jQuery.Event("keydown");
  e0.which = 49;
  var e1 = jQuery.Event("keypress");
  e1.which = 49;
  var e2 = jQuery.Event("keyup");
  e2.which = 49;
  $('textarea').trigger(e0).trigger(e1).trigger(e2);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<textarea></textarea>
<Br>
<button onclick='abc()'>
 press me to enter text with JS
</button>
<Br> 1) enter manully value and check console character char
<br>
<Br>2) trying to enter same event with Jquery but event trigger but value does not disply in textarea

<Br><br>testing with number "1" its charcode is 49
Kinglish
  • 23,358
  • 3
  • 22
  • 43