I\'ve read all the answers on to this questions and none of the solutions seem to work.
Also, I am getting the vibe that triggering keypress with special characters
console.log( String.fromCharCode(event.charCode) );
no need to map character i guess.
If you want to trigger the keypress or keydown event then all you have to do is:
var e = jQuery.Event("keydown");
e.which = 50; // # Some key code value
$("input").trigger(e);
In case you need to take into account the current cursor and text selection...
This wasn't working for me for an AngularJS app on Chrome. As Nadia points out in the original comments, the character is never visible in the input field (at least, that was my experience). In addition, the previous solutions don't take into account the current text selection in the input field. I had to use a wonderful library jquery-selection.
I have a custom on-screen numeric keypad that fills in multiple input fields. I had to...
On blur, save the current text selection (start and stop)
var pos = element.selection('getPos')
lastFocus.pos = { start: pos.start, end: pos.end}
When a button on the my keypad is pressed:
lastFocus.element.selection( 'setPos', lastFocus.pos)
lastFocus.element.selection( 'replace', {text: myKeyPadChar, caret: 'end'})
If you're using jQuery UI too, you can do like this:
var e = jQuery.Event("keypress");
e.keyCode = $.ui.keyCode.ENTER;
$("input").trigger(e);