How to visually simulate a keyboard key presses programmatically on a web page input field, using JavaScript and jQuery?
http://stackoverflow.com/q/39607003/5076162
HTML
<textarea></textarea>
JavaScript
//Source One - http://stackoverflow.com/a/2220234/5076162
//Source Two - http://stackoverflow.com/a/17881330/5076162
jQuery.fn.simulateKeyPress = function (character) {
// Internally calls jQuery.event.trigger
// with arguments (Event, data, elem). That last arguments is very important!
jQuery(this).trigger({ type: 'keypress', which: character.charCodeAt(0) });
};
jQuery(document).ready(function ($) {
// Bind event handler
$('textarea').keypress(function (e) {
//alert(String.fromCharCode(e.which));
console.log(String.fromCharCode(e.which));
var initialVal = $(this).text();
var newVal = initialVal.toString() + String.fromCharCode(e.which);
$(this).text(newVal);
console.log("New Value: " + newVal);
//String.fromCharCode(e.which)
});
// Simulate the key press
$('textarea').on('focus', function(e) {
//this could have been done with a for loop or the jQuery $.each() method by utilizing strings and arrays.
var str = '[email protected]';
for (var x = 0; x < str.length; x++)
{
var c = str.charAt(x);
$(this).simulateKeyPress('t');
}
// $(this).simulateKeyPress('t');
// $(this).simulateKeyPress('e');
// $(this).simulateKeyPress('s');
// $(this).simulateKeyPress('t');
});
$('textarea').focus();
});