How to trigger input event using jquery

I have the following that works:

$('textarea').keypress(function(e) { if (e.keyCode == '13') { alert('code'); } }); 

But I want to call the same thing when the page loads, I tried the following, but this does not work:

 var e = jQuery.Event("keypress"); e.which = 13; // Enter $('textarea').trigger(e); 

NOTE. I want my first code cut off, I DO NOT want to delete it.

+8
jquery
source share
3 answers

Use "which" instead of keyCode. What works in both scenarios

 $('textarea').keypress(function (e) { if (e.which == '13') { alert('code'); } }); 
+11
source share

Here is the solution for your problem http://jsfiddle.net/dima_k/zPv2a/

 $('button').click(function(){ debugger var e = $.Event("keypress"); e.keyCode = 13; // # Some key code value $('#textbox').trigger(e); }); $('#textbox').keypress(function(e) { if (e.keyCode == '13') { alert('code'); } }); 
+6
source share

Alternative solution:

 var textarea = $('textarea').keypress(OnTextareaKeypress); $(function(){ OnTextareaKeypress.call(textarea[0], { e: { which: 13 } }); }); function OnTextareaKeypress(e) { if (e.which == '13') { alert('code'); } } 
0
source share

All Articles