JavaScript to disable numbers in the text box

Business use case:

Create two text boxes  and put following client side validation to it.
  • Disable numbers to be printed
  • Enable only numbers
Implementation:

We can achieve the above business use case in at least two different ways by using java script on the client side. We can create a jsp or html page for the text box creation and we can call the java script function from there. 

test.jsp

<html>
<head>
<script src="script.js"></script>
</head>
<body>
    <fieldset>
        <legend>First way</legend>
        <table>
            <tr>
                <td>Only number field :</td>
                <td><input type="text" name="number"
                    onkeypress="return onlyNumbers(event)" /></td>
            </tr>

            <tr>
                <td>No digits field :</td>
                <td><input type="text" name="number"
                    onkeypress="return !onlyNumbers(event)" /></td>
            </tr>
        </table>
    </fieldset>
    <fieldset>
        <legend>Second way</legend>
        <table>
            <tr>
                <td>Only number field :</td>
                <td><input type="text" maxlength="10"
                    onkeypress="return validNo(this,event)" /></td>
            </tr>
            <tr>
                <td>No digits field :</td>
                <td><input type="text" maxlength="10"
                    onkeypress="return !validNo(this,event)" /></td>
            </tr>
        </table>
    </fieldset>
</body>
</html>


Now, below java script is the core ingredient of this example. Here, I'm writing two java script functions which essentially do the same thing.

script.js

function validNo(input, kbEvent) {
    var keyCode, keyChar;
    keyCode = kbEvent.keyCode;
    if (window.event)
        keyCode = kbEvent.keyCode;
    else
        keyCode = kbEvent.which;                                    
    if (keyCode == null) return true;
    keyChar = String.fromCharCode(keyCode);
    var charSet = "0123456789";
    if (charSet.indexOf(keyChar) != -1) return true;
    if (keyCode == null || keyCode == 0 || keyCode == 8 || keyCode == 9 || keyCode == 13 || keyCode == 27) return true;
    return false;
}

function onlyNumbers(e) {
    var keynum;
    var keychar;
    var numcheck;

    if(window.event) // IE
    {
        keynum = e.keyCode;
    }
    else if(e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }
    keychar = String.fromCharCode(keynum);
    numcheck = /\d/;
    return numcheck.test(keychar);
}




No comments:

Post a Comment