I would like to have an input element (type=text) or textarea element that validates dynamically by triggering specific keystrokes. This will be used for Chinese pinyin inp
You may not have much luck triggering keypress - I'm fairly sure that unless the keypress is trusted (i.e. originates from the browser), it won't be picked up.
However, you can do text replacement and insert the carat back where it was - instead of shooting it to the end of the string. You need to use setSelectionRange and createTextRange (for IE).
I've put together a little demo - the replacements you'll see don't match real words, but it shows how it works:
http://jsbin.com/emudi/ (to edit the source http://jsbin.com/emudi/edit)
The trick is to take note of where the carat is, replace the found word using substr (rather than regex to avoid replacing the wrong matches) and then re-placing the carat at the end of the new word.
The replacement is triggered on the space press or blurring the away. A note on this - you could trigger the replacement on a specific character (i.e. the '2') - but I wouldn't recommend searching for replacements on every keypress.
Also, for simple code controlling the "caret" in a cross-browser way this could be useful:
http://javascript.nwbox.com/cursor_position/
a bit late with the answer but I am sure you will still find this old stuff useful.