最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery simulate keypress on input - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 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);
发布评论

评论列表(0)

  1. 暂无评论