0

In the following script, when del key is pressed it returns 46 instead of 127, which is the ASCII code of del key.

function countLength(evt) {
            var inp = (evt.which) ? evt.which : event.keyCode;
            alert (inp);
            return true;
}

2 Answers 2

1

Values returned by event.keyCode are not ASCII codes. They just indicate which key was pressed on the keyboard. For example pressing 0-key on the topmost row of the keyboard returns 48, but pressing 0 on numberblock returns 96.

To convert keycodes to ASCII , you have to use some kind of an array containing corresponding values. In this task you have to check all other keys pressed simultaneously, like shiftKey and altKey to have correct results.

Sign up to request clarification or add additional context in comments.

3 Comments

The first paragraph is correct. However, there is no guaranteed mapping between key codes and character codes: this will vary between keyboard layouts and types. The only event that will give you reliable information about character codes is the keypress event, and when using that, you don't have to mess around with checking modifier keys such as Shift or Alt.
@TimDown That is true (self using scandinavian keyboard), but through keypress you can't have all keys pressed (delete for example). I was just about to add this issue to my answer, but it seems to be unnecessary, beacause it is in your comment already.
keypress detects everything printable, but it's true that it doesn't fire for non-printable keystrokes in all browsers. For detecting the Delete key I'd use keydown.
1

I am not sure where you are getting evt from becaue it is standalone function. If you are passing it then change:

event.keyCode;

To:

evt.keyCode;

Or try changing evt in all three cases to event or vice versa.

3 Comments

<form name="formA" id="formA" action="#" > <textarea id="txt" name="txt" onkeydown="return countLength(event)"></textarea> </form>
Try changing event to evt in all places and opposite of it for all again if it does not work.
@sandbox: That's weird then, there might be some other reason not sure though. I would use jQuery to solve it though.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.