4

I have a function that transforms the text to uppercase on keyup. The code looks like this (I think I found it on SO too):

$(selector).bind('keyup', function (e) {
  if (e.which >= 97 && e.which <= 122) {
    var newKey = e.which - 32;
    e.keyCode = newKey;
    e.charCode = newKey;
  }
  $(this).val((object.val()).toUpperCase());
});

The problem

In Chrome, when I type some text and then try to select it using shift + home, the cursor goes back to the last char, not selecting anything.

I also tested in Firefox and IE and it's working ok.

Please help me

Armel Larcier
  • 15,747
  • 7
  • 68
  • 89

2 Answers2

2

One of possible solutions is not changing value on every keyup, but just when the value actually changes:

$('#input').bind('keyup', function(e) {

    if (e.which >= 97 && e.which <= 122) {
        var newKey = e.which - 32;
        e.keyCode = newKey;
        e.charCode = newKey;
    }

    var oldVal = $(this).val();
    var newVal = oldVal.toUpperCase();

    if(oldVal != newVal)
    {
        $(this).val(newVal);
    }

});​

See it in JSFIDDLE.

Michal Klouda
  • 14,263
  • 7
  • 53
  • 77
2

There is a nice solution using only css here:

http://jsfiddle.net/46jrg/

just apply

text-transform: uppercase

to the text input region, and then you don't have to worry about that complicated javascript stuff. Less code means less bugs! :)

EDIT: When you select and copy the text, it will still be capitalized, but if you're submitting it to a server, you will have to either upcase it before send or upcase it when it gets there. This is normally no big deal though. Most common server-side languages can do it in a single method call.

Java has String::toUpperCase

PHP has the strtoupper function

Python has String::upper

Ruby has String::upcase

Perl has the uc function

Javascript has String::toUpperCase

C#.NET / VB.NET has String::ToUpper

Andbdrew
  • 11,788
  • 4
  • 33
  • 37