Click here to Skip to main content
15,895,011 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
hi all ,
i want to make function in javascript which can prevent user from writing letters in textbox only allow number
i found this one
JavaScript
function prevent_number(event)
   {
       var charcode = (event.which) ? event.which : event.keycode
       if (charcode >31 &&(charcode<48||charcode >57))
        {


            alert('please enter only number ');
            return false;

       }
       else
        {


           return true ;

       }





   }


i want to know why he said charcode>31 &&(charcode<48||charcode>57)
the numbers from 0 to 9 their code is just from 48 to 57
Posted

charcode >31

is redundant, the following will do:
if (charcode<48 || charcode >57)
 
Share this answer
 
v2
Comments
fady_hasnaa 7-Apr-14 1:02am    
so what if i write
if (charcode>57)
?
Peter Leow 7-Apr-14 1:07am    
You would have omitted checking of such characters like space, +, - etc. Look at the ASCII table provided by Abhinav S in this solution.
Peter Leow 7-Apr-14 3:26am    
I have done my part in answering, now it is your turn to accept the solution.
fady_hasnaa 7-Apr-14 15:29pm    
thanks my dear
Character code here represents the ASCII value of the character.
If you go through the character table at Ascii Table[^], you will get an idea why only these characters ranges are useful to you.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900