11

I have the following which works:

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

But I want to trigger that same thing when the page loads, I tried the following but it doesn't work:

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

NOTE: I want to have the first snipped of code there, I DO NOT want to remove it.

dzumla011
  • 592
  • 3
  • 7
  • 20

3 Answers3

14

Use "which" instead of keyCode. "Which" works in both scenario

$('textarea').keypress(function (e) {
    if (e.which == '13') {
        alert('code');
    }
});
Chirag Vidani
  • 2,519
  • 18
  • 26
6

Here is a 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');
    }
});
Dima Kuzmich
  • 1,286
  • 11
  • 18
  • 1
    isn't this a copy/paste of the answer here? http://stackoverflow.com/questions/832059/definitive-way-to-trigger-keypress-events-with-jquery – Omar Jul 16 '13 at 14:05
  • 2
    Take a look on a question. I believe, he already found the solution you attached, but it didn't work for him. So I attached a jsFiddle with working solution just to show that it works. – Dima Kuzmich Jul 16 '13 at 14:18
0

Alternative solution:

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

function OnTextareaKeypress(e) {
    if (e.which == '13') {
        alert('code');
    }
}
karaxuna
  • 26,752
  • 13
  • 82
  • 117