0

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?

3
  • 1
    Your JSFiddle works fine on my browser (Chrome). Commented Mar 9, 2017 at 1:32
  • 1
    It's fine with me as well. What seems to be the problem? 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. Commented Mar 9, 2017 at 1:34

1 Answer 1

2

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.

JSFiddle

$('input').on('keypress', function(){
    $('p').text("worked");
});

var e = jQuery.Event("keypress");
e.which = 13;
$("input").focus().val('test').trigger(e);
Sign up to request clarification or add additional context in comments.

1 Comment

Works now! Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.