0

I want to change behavior of my keyboard so when user on an input box press key a a = 97 it changes to b 97+1.

I want it for cross browser

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Luhana
  • 1

2 Answers2

1

jQuery.keypress will get you the event when the users types something, and String.fromCharCode gets you the character + 1. The tricky part is dealing with the selection.

To get the selection, I used the jQuery field selection plugin, and to make sure it doesn't keep jumping back to the end I used this answer to another question. Here is the final code:

$(function() {
    $("#target").keypress(function (evt) {
        if (evt.which >= 65 && evt.which <= 122) {
            var sel = $(this).getSelection();
            var val = $(this).val();
            var out = val.substring(0, sel.start) + String.fromCharCode(evt.which+1) + val.substring(sel.end, val.length);
            $(this).val(out);
            $(this).selectRange(sel.start + 1, sel.start + 1);
            return false;
        }
    });
});

jsFiddle

I restricted it to a-zA-Z but you can customize that however you want.

Community
  • 1
  • 1
David Fullerton
  • 3,224
  • 27
  • 38
  • Thought of this too, but what about the case when user change the caret position? It cause the new letter to appear in the end instead of in the caret position. I created quick test case for this: http://jsfiddle.net/yahavbr/teeW9/ – Shadow The GPT Wizard Mar 29 '11 at 23:29
  • great stuff, and even cross browser! :) Well, can't give more than the +1 I already gave. BTW your answer is missing the `selectRange` plugin. :) – Shadow The GPT Wizard Mar 29 '11 at 23:53
0

I tested the following in Firefox and Chrome. Using "keypress" allows the use of other keys, and using charCode allows using lower and uppercase letters:

document.getElementById("textbox").addEventListener("keypress",function(event){
    event.preventDefault();
    this.value+=(String.fromCharCode(event.charCode+1))
},false);

I just now saw the jQuery tag, so you could also do:

$("#textbox").bind("keypress",function(event){
    event.preventDefault();
    this.value+=(String.fromCharCode(event.charCode+1));
});
clmarquart
  • 4,721
  • 1
  • 27
  • 23