Trigger the jQuery's keypress event on an input text

孤街醉人 提交于 2019-12-02 07:00:39

The mistake you're making is what you're expecting the jQuery's trigger method to do. If you check out the code you'll see that what it is doing is actually executing the jQuery registered event handlers not the DOM Level 3 events. Because it's only executing jQuery handlers you wont be causing the change event which is what you need to be triggered to update the value property of the textbox.

As per documentation

Any event handlers attached with .bind() or one of its shortcut methods are triggered when the corresponding event occurs.

$('#foo').bind('click', function() {
  alert($(this).text());
});
$('#foo').trigger('click');

In your case, it would be:

$('#example').bind('keydown', function(e) {
  alert("Pressed: " + e.keycode());
});
$('#example').focus().trigger('click');

Might be over simplifying things, but couldn't you simply alter the .val() (value) of the input field to simulate auto-written values?

You could simply set the value like this -

$("#example").val('Some auto-written value');

Of you could do something a little more visual like this -

var autoText = ['f','o','o','b','a','r'];
var characterIndex = 0;
var autoType = setInterval(function(){
  $("#example").val( $("#example").val() + autoText[characterIndex] );
  characterIndex++;
  if (characterIndex >= autoText.length){
    clearInterval(autoType);
  }
},_keystroke_interval);

The _keystroke_interval is the interval (in milliseconds) between the auto typed characters. The autoType interval variable will iterate through all the indexes of the autoText array and for each iteration it will append one character to the input field.

This will give you more of an auto-typing feel...

here is a working jsFiddle example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!