Triggering jQuery keystroke event in input text

As for the .trigger() method, Event object , which property, JS char codes and the code below, why the #example input #example not receive char a as an automatically recorded value? Didn't I understand 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
source share
3 answers

According to the documentation

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

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

In your case, it will be:

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

You might need to simplify, but you can't just change the .val() (value) of the input field to simulate auto-written values ?

You can just set a value like this -

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

You could do something 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); 

_keystroke_interval is the interval (in milliseconds) between automatically entered characters. The autoType interval variable will autoType over all the indices of the autoText array, and for each iteration it will add one character to the input field.

This will give you more sense of automatic printing ...

here's a working jsFiddle example

0
source

All Articles