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.
Page 1 of 2 12 LastLast
Results 1 to 15 of 20
  1. #1
    New to the CF scene
    Join Date
    Oct 2011
    Posts
    7
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Keypress capitalize function broken in IE9

    A common javascript function that capitalizes input as user types (onkeypress) no longer works as of IE9. Need a function that also works in IE 9 that doesn't not change method call or interface (as it's used in 150 places throughout application).


    CALL:
    [CODE]
    el.onkeypress = function(el) {
    return c_capitalizeInput(el);
    }
    [CODE]
    FUNCTION:
    [CODE]
    // Intercepts keyboard input and capitalizes keystrokes.
    // Call with onkeypress="return capitalizeInput(event);"
    // Compatible with both IE and Netscape/Mozilla
    function c_capitalizeInput(evt) {
    evt = (evt) ? evt : ((window.event) ? window.event : "");
    if (window.event) {
    // IE
    if ((evt.keyCode >= 97) && (evt.keyCode <= 122)) {
    evt.keyCode = evt.keyCode - 32;
    }
    return true;
    } else if (evt.which) {
    // Netscape and Mozilla
    key = evt.which;
    if ((key >= 97) && (key <= 122)) {
    key = key - 32;
    evt.target.value = evt.target.value + String.fromCharCode(key);
    return false;
    }
    return true;
    } else {
    return true;
    // Can't do anything for other browsers
    }
    }
    [CODE]

    Any suggestions to make this work in IE9?

  • #2
    Regular Coder
    Join Date
    Apr 2005
    Location
    Texas
    Posts
    448
    Thanks
    24
    Thanked 63 Times in 63 Posts
    This usually does the trick for me...

    <input type="text" onkeyup="this.value=this.value.toUpperCase()" />

  • #3
    New to the CF scene
    Join Date
    Oct 2011
    Posts
    7
    Thanks
    2
    Thanked 0 Times in 0 Posts
    That would be ideal if starting from scratch, but need to replace existing method that is widely used. Also, triggered by keypress . .

  • #4
    Regular Coder
    Join Date
    Apr 2005
    Location
    Texas
    Posts
    448
    Thanks
    24
    Thanked 63 Times in 63 Posts
    I think this is what your looking for though:

    Code:
    <script>
    el.onkeyup = function(){
     el.value=el.value.toUpperCase()
     }
    </script>
    If el is what I think then you should just be able to insert that to replace what you already have...

  • #5
    Regular Coder
    Join Date
    Apr 2005
    Location
    Texas
    Posts
    448
    Thanks
    24
    Thanked 63 Times in 63 Posts
    I find that keyup is usually preferable for me, but if you need keypress you would just replace the "keyup" with "keypress"

    Edit:
    I wouldn't recommend that though, I just tested it, and it's one character behind if you opt for keypress... keyup really is better...

  • Users who have thanked blaze4218 for this post:

    softwaredev34 (10-13-2011)

  • #6
    Regular Coder
    Join Date
    Apr 2005
    Location
    Texas
    Posts
    448
    Thanks
    24
    Thanked 63 Times in 63 Posts
    At the end of the day, I find that keypress just isn't as reliable. It often doesn't give me the results that I anticipate. But honestly, there's no reason you couldn't just do this:

    Code:
    <script>
    el.onkeypress = function(){
     el.value=el.value.toUpperCase()
     }
    el.onkeyup = function(){
     el.value=el.value.toUpperCase()
     }
    </script>

  • #7
    Regular Coder
    Join Date
    Aug 2010
    Posts
    974
    Thanks
    19
    Thanked 212 Times in 210 Posts
    I agree with Blaze that toUpperCase
    is a reasonable solution but this
    works everywhere I think ....

    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html lang="en">
    <head>
    <meta name="generator" content="daveyerwin">
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title>SJax</title>
    <script type="text/javascript">
    function c_capitalizeInput(evt) {
    	evt=evt||event;
    	key=evt.which||evt.keyCode;
    	target=evt.target||evt.srcElement;
    	if ((key >= 97) && (key <= 122)) {
    			key = key - 32; 
    			target.value = target.value + String.fromCharCode(key);
    			return false;
    		} 
    }
    function init(){
     document.getElementById("inTxt").onkeypress=c_capitalizeInput;
    }
    </script>
    </head>
    <body onload="init()">
    <div id="container">
    <p><input type="text" id="inTxt"></p>
    </div> 	
    </body>
    </html>
    Last edited by DaveyErwin; 10-10-2011 at 05:20 PM.

  • #8
    Gütkodierer
    Join Date
    Apr 2009
    Posts
    2,127
    Thanks
    1
    Thanked 426 Times in 424 Posts
    That original code works in NO modern browser, except Firefox. Not Safari, not Chrome, not Opera, not IE9.

    That "Netscape" comment kind of gives it away that that code is ancient.

    blaze4218's suggestion will probably do what you want, if you make some changes to actually make it work with the keypress event:

    PHP Code:
    el.onkeypress = function () {
        var 
    self this;
        
    setTimeout(function () {
            
    self.value self.value.toUpperCase();
        }, 
    0);
    }; 
    keypress isn't "unreliable" — this is just a matter of execution order: It will do its thing before the input value is actually updated, so it's able to prevent key presses. Just use a setTimeout 0 to delay the action until the browser has become idle.

    Anyway, you have to be aware that, depending on what you are actually trying to accomplish here, that whole approach might be flawed: What if someone pastes text using their mouse? What if they have Javascript disabled?

    Those questions might be irrelevant, if this is for display purposes only. In that case, though, it's much better to just use the CSS property text-transform: uppercase.

    If, on the other hand, you're expecting uppercase input on the server, then you have to validate it there anyway, so just uppercase it there instead of hacking around on the client side.
    .My new Javascript tutorial site: http://reallifejs.com/
    .Latest article: Calculators — Tiny jQuery calculator, Full-fledged OOP calculator, Big number calculator
    .Latest quick-bit: Including jQuery — Environment-aware minification and CDNs with local fallback

  • #9
    Regular Coder
    Join Date
    Apr 2005
    Location
    Texas
    Posts
    448
    Thanks
    24
    Thanked 63 Times in 63 Posts
    "I find that keypress just isn't as reliable" was meant as an opinion, not fact. I thought I cleared that up with "doesn't give me the results that I anticipate"...
    Doing it's thing before the input value is updated is the problem of which I spoke. If I misrepresented opinion as fact I apologize.

  • #10
    Gütkodierer
    Join Date
    Apr 2009
    Posts
    2,127
    Thanks
    1
    Thanked 426 Times in 424 Posts
    Quote Originally Posted by blaze4218 View Post
    "I find that keypress just isn't as reliable" was meant as an opinion, not fact. I thought I cleared that up with "doesn't give me the results that I anticipate"...
    Doing it's thing before the input value is updated is the problem of which I spoke. If I misrepresented opinion as fact I apologize.
    Something not being reliable means to me that it sometimes works and sometimes fails, without any apparent reasons for the failures, which usually points to either a race condition or to not having understood the failure scenario very well — so I just wanted to clear up what it actually does; there's no need to apologize.
    .My new Javascript tutorial site: http://reallifejs.com/
    .Latest article: Calculators — Tiny jQuery calculator, Full-fledged OOP calculator, Big number calculator
    .Latest quick-bit: Including jQuery — Environment-aware minification and CDNs with local fallback

  • #11
    New to the CF scene
    Join Date
    Oct 2011
    Posts
    7
    Thanks
    2
    Thanked 0 Times in 0 Posts
    The onkeypress solution with the timeout (venegal) worked in some cases. . . but not in every case. I wanted to go this route because I didn't want to change the method call to onkeyup each time it was used.

    Here is the situation:

    It works when the function is called like either of these:a)
    Code:
     onkeypress="return c_capitalizeInput(this);"
    b)
    Code:
     function(el) {
              el.onkeypress = function() {
                       return c_capitalizeInput(el)
               }
         }

    It does not work when it is called like either of these:
    a)
    Code:
     onkeypress="return c_capitalizeInput(event);"
    b)
    Code:
     function(el) {
              el.onkeypress = function(el) {
                       return c_capitalizeInput(el)
               }
         }

  • #12
    New to the CF scene
    Join Date
    Oct 2011
    Posts
    7
    Thanks
    2
    Thanked 0 Times in 0 Posts
    DaveyErwin, I had tried the same solution as well . . . and was happy with how it worked until I realized that the maxlenth was no longer obeyed. This had always been true for Firefox, but now was also apparent in IE.

  • #13
    Gütkodierer
    Join Date
    Apr 2009
    Posts
    2,127
    Thanks
    1
    Thanked 426 Times in 424 Posts
    Quote Originally Posted by softwaredev34 View Post
    The onkeypress solution with the timeout (venegal) worked in some cases. . . but not in every case.
    Does that mean that among those 150 calls, all of those 4 cases you listed are actually implemented? The code I posted relies on this referring to the input element, but if you have no control over what this will actually be, it won't do you any good.

    If DaveyErwin's code works for you, you can just go with that — all you have to do is add a target.maxlength check to the part where you concatenate to target.value.

    It's still flawed, though, like I mentioned in my first post, and I'd still recommend using CSS or a server side filter (or both), depending on what you are actually trying to accomplish here.
    .My new Javascript tutorial site: http://reallifejs.com/
    .Latest article: Calculators — Tiny jQuery calculator, Full-fledged OOP calculator, Big number calculator
    .Latest quick-bit: Including jQuery — Environment-aware minification and CDNs with local fallback

  • Users who have thanked venegal for this post:

    softwaredev34 (10-13-2011)

  • #14
    Senior Coder Logic Ali's Avatar
    Join Date
    Sep 2010
    Location
    London
    Posts
    1,028
    Thanks
    0
    Thanked 207 Times in 202 Posts
    Include this once in each involved document, as-is or as a .js file.

    No configuration required.

    Code:
    <script type="text/javascript">
    
    (function()
    {
        /* Capitalise typed content of all text inputs and textareas unless "noCaps" is part of their 'class' attribute */
        
        function installHandler( obj, evt, func )
        {
          window.attachEvent ? obj.attachEvent( evt, func ) : obj.addEventListener( evt.replace(/^on/i, ""), func, false ); 
        }
        
        installHandler( document, 'onkeyup', function( e )
        {
          var evt = e || window.event,        
              srcElem = evt.target || evt.srcElement;
           
          if( !srcElem.className.match( /\bnoCaps\b/ ) && ( srcElem.nodeName == 'TEXTAREA' || ( srcElem.nodeName == 'INPUT' && srcElem.type == 'text' ) ) )
            srcElem.value = srcElem.value.toUpperCase();
            
        } );
       
    })( /*2843294C6F67696320416C69*/ );
    
    </script>
    Last edited by Logic Ali; 10-11-2011 at 02:30 PM.

  • #15
    New to the CF scene
    Join Date
    Oct 2011
    Posts
    7
    Thanks
    2
    Thanked 0 Times in 0 Posts
    For the common method, c_capitalizeInput(el), I was able to update the function to be backward compatible with the following:

    Code:
    function c_capitalizeInput(evt) {
    	
    	// use the value of event if available 
    	// if not assume it's IE and use window.event
    	evt=evt||window.event; 
    	
    	//return keycode in Firefox or IE
    	key=evt.which||evt.keyCode; 
    	
    	//return target element in Firefox or IE
    	target=evt.target||evt.srcElement;
    	
    	//check to see if the key that was pressed is a lowercase letter
    	if ((key >= 97) && (key <= 122)) {
    			//subtract 32 to get uppercase value
    			key = key - 32; 
    			//only append value if maxlength not exceeded
    			if (target.maxLength > target.value.length){ 
    				//append uppercase value to existing value
    				target.value = target.value + String.fromCharCode(key); 
    			}
    			return false;
    	} 
    		return true;
    	
    }
    However, the behavior was still less than perfect because any highlighted data in the field was either appended to or not replaced (if at the maxlength). Therefore, I deprecated this method.

    Going forward, the following method will be used.

    Code:
    function c_upper(el){
    	el.value=el.value.toUpperCase()
    }


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

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