Thursday, 26 January 2017

Javascript function which only allow numbers to be typed in textbox

Below Javascript function only allow number/integers to be typed in textbox. This function also don't allow any special symbol or any special character. If you type any character or special symbol in textbox it will reject to accept ,you can also show any error message through alert box.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function numbersonly(form_element, e) {
 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) ) {
       return true;
    }
    else if ((("0123456789").indexOf(keychar) > -1)) {
       return true;
    }
    else
       return false;
}

Now below code is showing how to call above javascript function so that textbox can only accepts numbers.

1
<input type="text" id="mobile" name="mobile" onkeypress="return numbersonly(this, event);">



      
Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.

This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.



No comments:

Post a Comment