SitePoint Sponsor

User Tag List

Results 1 to 7 of 7

Threaded View

  1. #1
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)

    Response to Javascript Force Numeric Input article

    Article: Javascript Force Numeric Input

    This article is about forcing the keyboard input fields of form inputs to accept only valid numbers, and Gary (the author) wants to know how to modify his script to be cross-browser compatible.

    With the way the script currently is, there are a couple of issues that have to be addressed for cross-browser support. These issues are:
    • Preventing keystrokes
    • Keycode compatibility
    • Passing the event


    Preventing Keystrokes

    Non-IE browsers use a different event model from IE, so preventing keystrokes is performed in a different manner. Setting different event properties may work in a majority of the cases, but the guaranteed way to success is to just return true or false to the event itself. That can be easily achieved by setting an "allowed" variable in the code and returning it at the end of the function.

    Code javascript:
    function forceNumericInput(arguments) {
        var allowed = false;
        // perform a number of tests
        if (key >= '0' && key <= '9') {
            allowed = true;
        }
        ...
        return allowed;    
    }

    Keycode Compatibility

    The keydown events are the biggest problem. Keys like the fullstop have different codes across different browsers. The <a href="http://unixpapa.com/js/key.html">Javascript Madness: Keyboard Events</a>[<a href="http://unixpapa.com/js/key.html" target="_blank" title="New Window">^</a>] article does a good job of explaining the problem.

    The solution is to set the event on keypress instead. When you do that the navigation keycodes won't be required anymore, and you can use String.fromCharCode(event.keyCode) to retrieve the key that was pressed as a normal string character.

    Code javascript:
    var key = String.fromCharCode(event.keyCode);
    switch(key) {
    ...
    case '.':
        ...
        break;
    }

    Passing the event

    Events can be successfully passed from html by using the event keyword in all browsers.

    Code javascript:
    <label>Number <input id="myNumber" type="text" onkeypress="return forceNumericInput(this, true, true, event)"></label>

    This is not the preferred way to do it, but is might be more compatible with your intended user base. There's a lot more to see about events at http://www.quirksmode.org/js/introevents.html

    The code that I came up with to resolve these issues (plus a few more) is:

    Code javascript:
    function forceNumericInput(el, allowDot, allowMinus, event) {
        var allowed = false,
            key = String.fromCharCode(event.charCode || event.keyCode);
        switch(key) {
        case '-':
           	if(allowMinus === true) {
                allowed = true;
                // wait until the element has been updated to see if the minus is in the right spot
                setTimeout(function (el) {
                   return function () {
                       removeNonstartingMinus(el);
                   };
                }(el), 250);
            }
            break;
        case '.':
            if(allowDot === true) {
                allowed = true;
                if(el.value.indexOf(".") > -1) {
                    // don't allow more than one dot
                    allowed = false;
                }
            }
            break;
        default:
            if (key >= '0' && key <= '9') {
               allowed = true;
            }
        }
        return allowed;
    }
    function removeNonstartingMinus(el) {
        var s = el.value,
            i = s.lastIndexOf("-");
        // if "-" exists then it better be the 1st character
        if(i > 0) {
            el.value = s.substring(0,i) + s.substring(i+1);
        }
    }
    Last edited by paul_wilkins; Oct 5, 2008 at 20:24.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •