Thursday, October 4

Textbox allows only numbers: javascript



//Html/ Jsp textbox which only allow numbers
//only numbers allowed in textbox

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