Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger enter event with jquery [duplicate]

Tags:

jquery

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.

like image 235
dzumla011 Avatar asked Jul 16 '13 13:07

dzumla011


2 Answers

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

$('textarea').keypress(function (e) {
    if (e.which == '13') {
        alert('code');
    }
});
like image 138
Chirag Vidani Avatar answered Nov 09 '22 11:11

Chirag Vidani


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');
    }
});
like image 6
Dima Kuzmich Avatar answered Nov 09 '22 11:11

Dima Kuzmich