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

2 Answers 2

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.

2
  • 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: jsfiddle.net/yahavbr/teeW9 Mar 29, 2011 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. :) Mar 29, 2011 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));
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.