1$.fn.replaceCharOnKeyPress = function(chr, replacement) {
2 var moveCursorBy = replacement.length - chr.length;
3 this.each(function() {
4 $(this).keypress(function(e) {
5 if (e.key == chr) {
6 // IE
7 if(document.selection) {
8 // Determines the selected text. If no text selected, the location of the cursor in the text is returned
9 var range = document.selection.createRange();
10 // Place the replacement on the location of the selection, and remove the data in the selection
11 range.text = replacement;
12 }
13 // Chrome + FF
14 else if(this.selectionStart || this.selectionStart == '0') {
15 // Determines the start and end of the selection.
16 // If no text selected, they are the same and the location of the cursor in the text is returned
17 // Don't make it a jQuery obj, because selectionStart and selectionEnd isn't known.
18 var start = this.selectionStart;
19 var end = this.selectionEnd;
20 // Place the replacement on the location of the selection, and remove the data in the selection
21 $(this).val($(this).val().substring(0, start) + replacement + $(this).val().substring(end, $(this).val().length));
22 // Set the cursor back at the correct location in the text
23 this.selectionStart = start + moveCursorBy + 1;
24 this.selectionEnd = start + moveCursorBy + 1;
25 }
26 else {
27 // if no selection could be determined,
28 // place the replacement at the end.
29 $(this).val($(this).val() + replacement);
30 }
31 return false;
32 }
33 });
34 });
35 return this;
36};
37