开发者

Javascript keycode =/= charcode

I'm binding开发者_如何学运维 on the keydown event with jQuery to allow some specific characters in a textbox. I'm trying to make my code cross browser and platform compliant. My main issue is that I can't find a way to map the received key-code to a valid char-code, especially for key code coming from the numeric pad (decimal separator, is it a comma or a period, etc.).


That is correct. There is no such mapping you can do; a keydown may not even correspond to a character being inserted. Or Caps Lock might change the meaning of the keypress, and you can't sniff for that. And various other wrinkles.

If you want to know the character code your only option is to use the keypress event.


Well, if your problem is translation of the keycodes to characters, why not let the browser handle it for you? This might sound hideous, but you could simply allow the browser modify the text box (so that delete is a delete, and a period is a period), and then go back and edit it... Um... maybe something like this:

function hookEvents() {
    $('#myTextBox').oldValue = $('#myTextBox').value;
    $('#myTextBox').bind('keyup', function(event) {
        // Maybe nothing's changed?
        if (event.target.oldValue == event.target.value) {
            return;
        }

        var validInput = /(\-?[0-9]*(?:\.[0-9]*)?)/;
        var input = event.target.value;
        var result = validInput.exec(input);
        if (result.index != 0 || result[result.length-1] != input.length) 
        {
            event.target.value = result[0];
        }

        // update for later
        event.target.oldValue = event.target.value;
    });
}

The biggest problem with this approach is that every key pressed appears on screen for a moment. On the other hand, with the REGEX you have a lot more control over the format of the allowed input. In the example above, I only allow positive or negative numbers (with an optional decimal point). Such as: "123", "-123", "-123.456", "123.456".

I know this doesn't really answer your question, but it sidesteps the issue entirely!


Well, like I said in comments, the goal behind this question was to filter a textbox on numeric values. I managed to reach my goal using the keypress event.

I've published a jQuery plug-in for those who are interested in the solution.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜