Mike Deluca
Mike Deluca

Reputation: 1210

jQuery keypress event trigger not working on page load

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);
});

Upvotes: 0

Views: 2521

Answers (2)

Aruna
Aruna

Reputation: 12022

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" />

Upvotes: 1

Ibu
Ibu

Reputation: 43810

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);   

Upvotes: 0

Related Questions