Run keystroke with jQuery ... and indicate which key was pressed

I would like to have an input element (type = text) or textarea that will be dynamically checked by running certain keystrokes. This will be used to enter Chinese pinyin, for example:

The user enters "ma2" into the input element. The keydown event is fired for every keystroke, and 2 never appears. Instead, when the user presses "2", "a" will receive a tone mark, for example: "á". At the end, the user types: "má".

This can be achieved by reading and changing the entire input value using $ (element) .val (), however, when the input element has focus and its value is set by calling .val ("something"), the cursor moves to the end of the text. This works great in most situations because the user just keeps typing at the end of the field, but I want it to work in all situations.

... Another solution to this problem would be to get / set the cursor location inside an input element or textarea. However, I do not think this is possible in javascript.


So, Remy was on the right track. Trigger keystrokes will not allow me to enter special characters without much hassle. Instead, I catch the keydown event and set the input value / textarea, and then move the caret.

I did not find anything good for getting / setting a carriage in jQuery, but the following really violated this problem for me. I will write a link to my final pinyin input code when it is stable. This is pretty close.

http://blog.vishalon.net/Post/57.aspx http://demo.vishalon.net/getset.htm

+4
source share
2 answers

You may not have much luck when starting keypress - I am sure that if keypress is not trusted (i.e. not from the browser), it will not be raised.

However, you can replace the text and insert the carat back to where it was, instead of shooting at the end of the line. You need to use setSelectionRange and createTextRange (for IE).

- , , , , :

http://jsbin.com/emudi/ ( http://jsbin.com/emudi/edit)

, , , , substr ( , ), .

. - (.. "2" ), .

+8

All Articles