Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    May 2006
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Only Allow Digits and "/"

    I have a textbox on a form that is used for a date. I am trying to use javascript to prevent users from typing anything but numeric data or a "/". I have everything working but allowing the backslash. This is what my function looks like:

    Code:
    function allowDigits(evt)
    {
       var charCode = (evt.which) ? evt.which : event.keyCode
       
       if (charCode == 8 || charCode == 37 || charCode == 39)
            return true;
    
       if (charCode > 31 && (charCode < 48 || charCode > 57)) 
            return false;
    
     return true;
    }
    In the first if statement when I try and add charCode == 191 || charCode == 111 that doesn't work to allow the backslash. Any ideas? I am not sure what I am doing wrong.

    Thanks in advance!

  • #2
    Senior Coder
    Join Date
    Jul 2005
    Location
    New York, NY
    Posts
    1,084
    Thanks
    4
    Thanked 19 Times in 19 Posts
    Why check on every keypress? Why not use a regular expression once they finished typing?

    In other words, I don't know the answer to your question.

    The simplest would be that slash is not 191 or 111

  • #3
    Senior Coder coothead's Avatar
    Join Date
    Jan 2004
    Location
    chertsey, a small town 25 miles south west of london, england.
    Posts
    1,696
    Thanks
    0
    Thanked 232 Times in 227 Posts
    Hi there xxwhocaresxx,

    and a warm welcome to these forums.

    Try it like this...
    Code:
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>numbers and /'s only</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <style type="text/css">
    /*<![CDATA[*/
    fieldset {
       border:0 solid;
     }
    /*//]]>*/
    </style>
    
    <script type="text/javascript">
    //<![CDATA[
    window.onload=function() {
       document.forms[0][1].onkeyup=function() {
    if(this.value.match(/([^\d\/])$/)) {  
       alert('Come on stop messing about.\nthis box is for numbers and"/\'s" only.\nWe do not want to see any "'+RegExp.$1+'\'s" here thank you.');
       document.forms[0][1].value=this.value.replace(RegExp.$1,''); 
       }
      }
     }
    //]]>
    </script>
    
    </head>
    <body>
    
    <form action="#">
    <fieldset>
    <input type="text"/>
    </fieldset>
    </form>
    
    </body>
    </html>
    
    coothead


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •