0

I am trying to simulate an enter keypress for an input on page load, however it doesn't appear to be working. I only find success when I click in the input and press enter. I expect to see the alert when the page loads.

If you change the order I have listed below, then it provides an alert, but the key that is pressed is undefined.

Any ideas where I am going wrong here?

See demo here - http://jsfiddle.net/3xTM2/1321/

HTML

<input id="test" type="text" />

Javascript

$('#test').trigger(jQuery.Event('keypress', { keycode: 13 }));    
$('#test').keypress(function(e) {
  alert(e.keyCode);
});
Aruna
  • 11,959
  • 3
  • 28
  • 42
Mike Deluca
  • 1,295
  • 2
  • 18
  • 41
  • This is a duplicate question... See this answer: http://stackoverflow.com/a/832121/2159528 – Louys Patrice Bessette Mar 27 '17 at 23:57
  • 1
    You are triggering the event before defining it. Just change the order. – Ibu Mar 27 '17 at 23:57
  • 1
    Possible duplicate of [Definitive way to trigger keypress events with jQuery](http://stackoverflow.com/questions/832059/definitive-way-to-trigger-keypress-events-with-jquery) – Louys Patrice Bessette Mar 27 '17 at 23:58
  • @Ibu if you change the order, then it provides an alert, but the key that is pressed is undefined. – Mike Deluca Mar 28 '17 at 00:02
  • 1
    Your fiddle is using jQuery 1.4.2 and documentation says: `As of jQuery 1.6, you can also pass an object to jQuery.Event() and its properties will be set on the newly created Event object.` – Mr_KoKa Mar 28 '17 at 00:10
  • It works [`just fine`](http://jsfiddle.net/websiter/9cc7x9pv/). – tao Mar 28 '17 at 00:10
  • @MikeDeluca You can check my answer below with the change of order and the change in the upper case in `Code` instead of `code` – Aruna Mar 28 '17 at 00:15

2 Answers2

1

As mentioned in the comment, just change the order and change keycode to keyCode as below.

Note: Please note the upper case in Code instead of lower case in code

$('#test').keypress(function(e) {
  alert(e.keyCode);
});



$('#test').trigger(jQuery.Event('keypress', { keyCode: 13 }));    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="test" type="text" />
Aruna
  • 11,959
  • 3
  • 28
  • 42
0

You have to reverse the order, and assign the data to the event object on your version of jQuery:

$('#test').keypress(function(e) {
  alert(e.keyCode);
});

var event = jQuery.Event('keypress');
event.keyCode = 13;
$('#test').trigger(event);   
Ibu
  • 42,752
  • 13
  • 76
  • 103