Wednesday, 9 October 2013

How to restrict the entry of alphabets in a textbox using javascript




In this article I will explain how to restrict the entry of alphabets in a textbox.


Why do we need to restrict

In our application we may have a field like a phone numbers field or a number entry field. Here we need to enter only numbers. There are few validation methods which generate an alert message when we click the submit button or when we move the cursor from that textbox. But we can write a keypress event which restricts the entry of alphabets i.e. when you press the keys, or buttons other than 0 to 9; they are not entered into the textbox. This reduces the validation coding.

Now let’s have a look at the code



Take text box

<input type="text" id="txtPhoneNumber" name="txtPhoneNumber"/>
Now we will write a key press event to the textbox ‘txtPhoneNumber
<script type=”text/javascript”>
The key press event of the text box txtPhoneNumber is written as
$('#txtPhoneNumber').keypress(function (e)
 {

Now we will take the ASCII (American Standard Code for Information Interchange) values of the numbers from zero to nine. Their ASCII codes are as follows
0=48
1=49
2=50
3=51
4=52
5=53
6=54
7=55
8=56
9=57
We will also allow back space button. Back space ASCII value is
8=back space
Now the whole code is
$('#txtPhoneNumber').keypress(function (e) {
                    var key_codes = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0, 8];
                    if (!($.inArray(e.which, key_codes) >= 0)) {
                        e.preventDefault();
                    }
                });
            </script>
This function will not allow any alphabets or the special characters in that particular textbox

1 comment: