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>
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...
来源:https://stackoverflow.com/questions/10685520/trigger-the-jquerys-keypress-event-on-an-input-text