Saturday 6 October 2012

How do I make a textbox that only accepts numbers

1. Html/ Jsp textbox which only allow numbers
2. Only numbers allowed in textbox
3. How can I use javascript to allow only numbers to be entered in a textbox
4. Allow only Numbers in a Textbox
5. Textbox number validation

//Javascript code below
function numbersOnly(myfield, 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);
           
            // control keys
            if ((key==null) || (key==0) || (key==8) ||
               (key==9) || (key==13) || (key==27) )
              return true;
           
            // numbers
            else if ((("0123456789.").indexOf(keychar) > -1))
              return true;
            // decimal point jump
            else
              return false;
   }
// JSP code 

use the above javascript function @ onKeyPress event like below

<s:textfield name="textbox1" id=" textbox1" maxlength="20" onkeypress="return numbersOnly(this, event);" />
// <s:textfield> is a struts tag. Html <input> tag can also be used.

No comments:

Post a Comment