Trigger the jQuery's keypress event on an input text

倖福魔咒の 提交于 2019-12-02 13:23:04

问题


Regarding the .trigger() method, the Event object, the which property, the JS char codes and the code below, why does the #example input don't get the char a as auto-written value? Did I misunderstand the .trigger() method?

<input type="text" name="example" id="example" value="" />

<script>
$(function() {
    var e = jQuery.Event("keydown", { which: 65 });
    $("#example").focus().trigger(e);
});
</script>

回答1:


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.




回答2:


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');



回答3:


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



来源:https://stackoverflow.com/questions/10685520/trigger-the-jquerys-keypress-event-on-an-input-text

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