www.webdeveloper.com
Results 1 to 15 of 15

Thread: Detecting certain keys onkeydown

  1. #1
    Join Date
    Jan 2008
    Location
    ncl,uk
    Posts
    56

    Question Detecting certain keys onkeydown

    What i need is something as such (based on previous thread): I have a textfield and i want to limit the input to only numbers, letters and caps.
    So the code is:
    <input onkeydown="return testChars(event)" type="text" .../>
    function testChars(e)
    {

    var keyCode = e.keyCode;

    if(e.shiftKey && keyCode==53){
    return false;
    } //block "%"
    //HERE BLOCK EVERYTHING THATS NOT a Letter, caps and numbers

    if ( (keyCode > 64 && keyCode < 91) ||(keyCode > 96 && keyCode < 123) )//Letters and Caps
    {
    return true;
    }
    else if ( keyCode > 47 && keyCode < 58 )//numbers
    {
    return true;
    }


    }

    The problem however using the onkeydown is that i would need to cater for every single possibility of them using SHIFT+1=*, SHIFT+2, SHIFT+3 etc. which would take forever. And i cant block Shift because they might use it for Capitalising letters.
    What is the best way to do this, im abit puzzled here...

  2. #2
    Join Date
    Apr 2003
    Location
    Netherlands
    Posts
    21,654
    Aren't you overthinking this? Who is going to use 'shift+1' ? The form values will have to be validated server side anyway.

  3. #3
    Join Date
    Jan 2007
    Location
    Wisconsin
    Posts
    2,120
    Well, shift+1 is an exclamation point -- not a terribly uncommon thing to type! (Unless you're referring to shift+[start of heading], which us un-type-able, I think.) Though Fang is right: form entry needs to be checked on the server-side.

    To address the specific question though, see http://www.quirksmode.org/js/keys.html

    So, my assumption is that you want to filter keys onkeypress using something like the following:
    Code:
    <input type='text' onkeypress='return filter()'; />
    <script type='text/javascript'>
      function filter(in_event) {
        var e = in_event || window.event;
        var typedChar = String.fromCharCode(e.charCode || e.keyCode);
        if (typedChar.match(/a-zA-Z0-9/)) {
          return true;
        } else {
          return false;
        }
      } // filter()
    </script>
    The above code is untested ... but I think that's generally the direction you want to take this. I actually might update my auto-completer code on svidgen.com with something like this later ... If I get around to that today, I'll post my code.

  4. #4
    Join Date
    Jan 2008
    Location
    ncl,uk
    Posts
    56
    Thanks both for the reply,
    Fang you would be suprised how many people just type junk into form fields (I have a large database of members to prove this) so the idea is just to prevent random things being typed into the fields. Server side code also exists to double check errors too however there are certain fields that JS would be sufficient to do all the checking.

    svidgen cheers for that i will give it a try when im back in office on Monday, the reason why i didnt use keypress before was because i was recommended to use onkeyup/down because of inconsistencies between browsers which gave me extremely bad headaches as you can imagine . I rekon using the String.fromCharCode to detect characters might be a better idea than checking keyCodes. I will give it a whirl and post back .

  5. #5
    Join Date
    Jan 2008
    Location
    ncl,uk
    Posts
    56
    Hi again,
    Ok after testing the code unfortunately svidgen your code does not work. The reason being is that if you do:
    if (typedChar.match(/[0-9]/)) { //this is only an example if i was using numbers only
    return true;
    }
    Then when you press the 'Backspace' button, left arrow key, right arrow key or tab none of those commands work in Firefox because the typedChar.match does not return true. It does however work only in IE. The only way i can think of solving this is by doing something like this (which again is back to square one of capturing many events):
    Code:
    if (typedChar.match(/[0-9]/)) {
    	return true;
    } 
    else{
    	if(e.keyCode==8 || e.keyCode==37 || e.keyCode==39 || e.keyCode==9) //backSPC,left, right, tab 
           {
    	    return true;
           }
    
    }
    return false;
    }
    Does anyone see any other intelligent solution to this problem?

  6. #6
    Join Date
    Apr 2003
    Location
    Netherlands
    Posts
    21,654
    Put all keyCodes in an array then see if the code is in the array.

  7. #7
    Join Date
    Jan 2008
    Location
    ncl,uk
    Posts
    56
    I actually had it in an array the first time however you will still have to cater for things like "CTRL+A", "SHIFT+left arrow", "SHIFT+right arrow" etc. This if ofcourse if you are using onkeyup/down, if you use onkeypress then you need to cater for other things like "SHIFT+5" having the same code as "left arrow key" etc and if you allow a charCode in IE then you might also be allowing keyCodes in firefox by using the evt || event.keyCode.

    I think u were right the first time, this is becomming way over-complicated, i think i will just scrap the idea as there seems endless possibilities i can not cater for .

  8. #8
    Join Date
    Apr 2003
    Location
    Netherlands
    Posts
    21,654
    Run a regex onblur to remove unwanted characters.

  9. #9
    Join Date
    Jan 2009
    Posts
    3,346
    Quote Originally Posted by Fang View Post
    Run a regex onblur to remove unwanted characters.
    Or onchange if you want to do it like the banks do. (This causes a flicker you may or may not find acceptable).

  10. #10
    Join Date
    Jan 2008
    Location
    ncl,uk
    Posts
    56
    Im actually already detecting for errors at the point that they click the submit button (before submission though) so i guess i could use an onBlur/change instead of the onkeyup/down. This onkeyup/down/press is a major headache especially since of browser compatibility issues so id advise anyone reading this post to stay away from it .
    Thanks all for advice anyways though

  11. #11
    Join Date
    Apr 2003
    Location
    Netherlands
    Posts
    21,654
    I do find it the wrong thing to do; blocking keystrokes. The user has no feedback and no flexibility of input.

    As an example, the Dutch postal code is 4 numbers followed by 2 alphabetic characters.
    There is nothing incorrect in the user having a space between the two. How often do I see this blocked or returned from the server as invalid and consequently deleted.
    User enters "1234 ab", valid and stored as "1234AB". The programmer does the work.
    Stop annoying the user.

  12. #12
    Join Date
    Jan 2007
    Location
    Wisconsin
    Posts
    2,120
    Quote Originally Posted by Fang View Post
    I do find it the wrong thing to do; blocking keystrokes. The user has no feedback and no flexibility of input.

    As an example, the Dutch postal code is 4 numbers followed by 2 alphabetic characters.
    There is nothing incorrect in the user having a space between the two. How often do I see this blocked or returned from the server as invalid and consequently deleted.
    User enters "1234 ab", valid and stored as "1234AB". The programmer does the work.
    Stop annoying the user.
    I actually disagree somewhat. The fact that form controls accept input that isn't valid seems like a bug to me. I'd rather see bad keystrokes filtered out and see some indication of bad input on the screen at the time of entry than wait for the page to reload to see a list of what I've done wrong. To me, that is annoying.

    Putting tight-nit filters in place on forms is primarily a courtesy to the user.

  13. #13
    Join Date
    Jan 2008
    Location
    ncl,uk
    Posts
    56
    That was also my logic behind it svidgen, basically if i dont want them to use rogue characters in a username then if the keystroke doesnt work they would know immediately rather than later. I dont really see anything annoying about eliminating errors at the earliest possible stage. A simple example of this is not wanting users to have a username of "/*-/-*/-*/-/-///", you would be suprised how many people enter junk into their username and then just forget what their username is and have to call up/email to retrieve it (And this is just a small example)...

  14. #14
    Join Date
    Jan 2009
    Posts
    3,346
    I would recommend some visible feedback such as: "You have entered an invalid character" as a nicety rather than just not displaying the invalid character. I know I would be confused as a user if what I was typing just wasn't showing up (I might think something was wrong with my keyboard).

  15. #15
    Join Date
    Jan 2008
    Location
    ncl,uk
    Posts
    56
    I actually had an error message appear next to the field to tell them they were entering wrong data on the spot. Not that it matters now since im not using the onkeypress anymore hehe.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

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



Recent Articles