I tried the answer here but it doesn't work for me.
JSFiddle: /
$('input').val('test').trigger(jQuery.Event('keypress', {keycode: 13}));
$('input').on('keypress', function(){
$('p').text("worked");
});
What am I doing wrong?
I tried the answer here but it doesn't work for me.
JSFiddle: https://jsfiddle/Ldu6wwv0/
$('input').val('test').trigger(jQuery.Event('keypress', {keycode: 13}));
$('input').on('keypress', function(){
$('p').text("worked");
});
What am I doing wrong?
Share Improve this question edited May 23, 2017 at 11:53 CommunityBot 11 silver badge asked Mar 9, 2017 at 1:31 KalzoneKalzone 1312 gold badges3 silver badges10 bronze badges 3- 1 Your JSFiddle works fine on my browser (Chrome). – Joe Attardi Commented Mar 9, 2017 at 1:32
- 1 It's fine with me as well. What seems to be the problem? – Sean Kwon Commented Mar 9, 2017 at 1:33
- That's odd. I'm on chrome as well and it doesn't work -Version 56. I just tried on Safari, Firefox too.. no dice. – Kalzone Commented Mar 9, 2017 at 1:34
1 Answer
Reset to default 2The 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.
JSFiddle
$('input').on('keypress', function(){
$('p').text("worked");
});
var e = jQuery.Event("keypress");
e.which = 13;
$("input").focus().val('test').trigger(e);