Monday, January 24, 2011

Restricting to floating point number onkeypress

Very simple JavaScript code to restrict text box to have floating point number. Code is here-

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <title>Untitled Page</title>
 <script type="text/javascript">
     function restrict(val, e) {
         var keyChar;
         if (window.event)
             keyChar = String.fromCharCode(window.event.keyCode);
         else if (e)
             keyChar = String.fromCharCode(e.which);
         else
             return true;
         var number = parseFloat(val + keyChar);
         if (number != val + keyChar)
             return false;
         else
             return true;
     }
</script>
</head>
<body>
 <input name="number" onkeypress="return restrict(this.value, event)">
</body>
</html>