SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Wizard
    Join Date
    Apr 2002
    Posts
    2,301
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)

    allow only certain chars to be type into field while allowing function keys to functi

    i've got this code on a text field keypress handler:

    Code:
    function keypresshandler(e) {
    	var e = e || window.event;
    	var code = e.charCode || e.keyCode;
    	if(e.charCode == 0) {
    		return true;
    	}
    	if(e.ctrlKey || e.altKey) {
    		return true;
    	}
    	if(code < 32 || (code >= 63232 && code <= 63235) ) {
    		return true;
    	}
    	var c = String.fromCharCode(code);
    	if( c.search(/[0-9a-zA-Z ]/) != -1 ) {
    		//alert("true");
    		return true;
    	}
    	else {
    		//alert("false");
    		return false;
    	}
    }
    it's based on code from the o'rielly js def guide book. i added in the:
    || (code >= 63232 && code <= 63235)
    bit because i noticed the arrow keys were dissabled in safari when the text field had focus. but now i realise in safari when the text field has focus a whole load of things don't work, for example, while holding the apple key down and you press the comma key, usually the preferences window come up, but this is blocked.

    so what's the best way to allow safari's (and all other browser's if possible) function keys to all work while only allowing upper and lowercase letters, digits, and spaces to be typed into the text field?

    thanks.

  2. #2
    SitePoint Guru
    Join Date
    Sep 2006
    Posts
    731
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by johnyboy View Post

    so what's the best way to allow safari's (and all other browser's if possible) function keys to all work while only allowing upper and lowercase letters, digits, and spaces to be typed into the text field?
    Forget about reading keycodes and just run a filtering regex on keyup. It's simpler, infallible and allows the user to see unwanted characters being erased.
    Code:
    <textarea onkeyup="this.value=this.value.replace(/[^a-z0-9\s]/ig,'')"></textarea>
    Tab-indentation is a crime against humanity.

  3. #3
    SitePoint Wizard
    Join Date
    Apr 2002
    Posts
    2,301
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    i see. right, ok thanks.


Bookmarks

Posting Permissions

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