Reputation: 121
I tried the answer here but it doesn't work for me.
JSFiddle: https://jsfiddle.net/Ldu6wwv0/
$('input').val('test').trigger(jQuery.Event('keypress', {keycode: 13}));
$('input').on('keypress', function(){
$('p').text("worked");
});
What am I doing wrong?
Upvotes: 0
Views: 10544
Reputation: 205
The problem seems to be order of your code. Your code which triggers keypress is defined before the event handler.
This seems to work now. (JSFiddle)
$('input').on('keypress', function(){
$('p').text("worked");
});
$('input').val('test').trigger(jQuery.Event('keypress', {keycode: 13}));
UPDATE: Also Please don't use keycode as it is deprecated (link) and might not work in some cases. I've personally faced this issue. Use which instead.
$('input').on('keypress', function(){
$('p').text("worked");
});
var e = jQuery.Event("keypress");
e.which = 13;
$("input").focus().val('test').trigger(e);
Upvotes: 2