1

I'm working with a JavaScript routine I didn't write. It is called from a text box's onkeydown attribute to prevent unwanted keystrokes.

The first argument is apparently not used. The second argument is a list of characters that should be allowed.

function RestrictChars(evt, chars) {
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;

    keychar = String.fromCharCode(key);

    if ((key == null) || (key == 0) || (key == 8) ||
        (key == 9) || (key == 13) || (key == 27))
        // Control key
        return true;
    else if (((chars).indexOf(keychar) > -1))
        return true;
    else
        return false;
}

This seems to work for alpha-numeric characters. However, characters such as . and / cause this function to return false, even when these characters are included in the chars parameter. For example, if the . key is pressed, key is set to 190, and keychar gets set to the "3/4" character.

Can anyone see how this was meant to work and/or why it doesn't? I don't know enough about JavaScript to see what it's trying to do.

1

2 Answers 2

5

Two things are wrong with that: first, if you're analysing what character has been typed, you need to use the keypress event instead of keydown because that is the only event that tells you anything reliable about the actual character typed. For (a lot) more detail about about this and JavaScript key events in general, see http://unixpapa.com/js/key.html. Second, there are references to a variable called e which doesn't (but should) correspond with the evt parameter.

Here's a rewrite, assuming you have a variable called textBox that refers to the text input element.

jsFiddle: http://jsfiddle.net/9DZwL/

Code:

function isKeypressCharValid(e, chars) {
    e = e || window.event;

    // Allow delete, tab, enter and escape keys through
    if (/^(8|9|13|27)$/.test("" + e.keyCode)) {
        return true;
    }

    var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
    var charTyped = String.fromCharCode(charCode);
    return chars.indexOf(charTyped) > -1;
}

textBox.onkeypress = function(evt) {
    if (!isKeypressCharValid(evt, "abc123")) {
        return false;
    }
};
Sign up to request clarification or add additional context in comments.

16 Comments

Thanks. That seems to work. I'll read up on this but perhaps you could answer a couple of quick questions. 1) How come this doesn't prevent control characters such as backspace? 2) What the heck is || doing? (With my background, || is logical OR but that doesn't seem to make sense here.)
@Jonathan: I just added a bit to deal with control characters. || in JavaScript returns the first operand if it is "truthy" (i.e. coerces to Boolean true) and the second operand otherwise, so can be used as a shortcut in conditional assignment.
@pst: JavaScript key events are a mess. I suggest reading the page linked to in my answer (vastly superior to the quirksmode page, IMO) or my shorter summary here: stackoverflow.com/questions/4285627/… and then see if you think my answer's wrong.
@Ken: I outlined two reasons why it doesn't work: first, it's the wrong event, and second, there's an incorrect variable. Admittedly I didn't expand on what the code is trying to do, but I provided a link to a resource that explains in great detail exactly how JavaScript key events do work.
@Jonathah Wood: || is indeed logical OR. The code in the first if branch says "if key is equal to null OR key is equal to 0 or". As for your question about backspace, it's specifically part of that test with key == 8 (which is backspace; 9 is tab, 13 is enter (or return), and 27 is escape.
|
1

I'm not a JS person, either, but... I can explain how it's supposed to work; I don't know why you're getting the values you are for the keys you mentioned, however.

keychar = String.fromCharCode(key);

This checks to see if the key is a printable character (letter, punctuation mark, etc.)

if ((key == null) || (key == 0) || (key == 8) ||
    (key == 9) || (key == 13) || (key == 27))
    // Control key

The above checks to see if the key is null OR (||)` 0 or 8 (backspace) or 9 (tab) or 13 (0x0D, or ENTER) or 27 (0x1B or ESCAPE) - it's exactly the Boolean result you'd expect: IF <thiscondition> or <thatcondition> or <anothercondition> or ...

else if (((chars).indexOf(keychar) > -1))

This checks to see if the keychar is in the string of characters passed as the chars parameter

Comments

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.