views:

308

answers:

4

I would like to have an input that would change to upper case on keyup. So I attach a simple event on keyup.

HTML

<input id="test"/>

Javascript (with jQuery)

$("#test").keyup(function(){
  this.value = this.value.toUpperCase();
});

But I found that in Chrome and IE, when you push left arrow, the cursor automatically move to end. I notice that I should detect if the input is letter only. Should I use keycode range or regexp for detection?

Example: http://jsbin.com/omope3

A: 

You probably want to look at keyCode in your keyup function.

var UP_ARROW = 38,
    DOWN_ARROW = 40;

$('#test').keyup(function(evt){
    if (evt.keyCode == UP_ARROW)
    {
        this.value = this.value.toUpperCase();
    }

    if (evt.keyCode == DOWN_ARROW)
    {
        this.value = this.value.toLowerCase();
    }
});
Darrell Brogdon
+1  A: 

Yeah, looks like some browsers move the cursor to the end when the value gets updated. You could do this:

$("#test").keyup(function(){
  var upper = this.value.toUpperCase();
  if (this.value != upper) 
      this.value = upper;
});

which will only change the value if it needs to be changed. However, that still leaves you with the problem that if you type abd, move left, hit c to get abcd, the cursor will still get moved to the end.

Rob Van Dam
+4  A: 

Or you can use the following (this is probably faster and more elegant):

<input style="text-transform: uppercase" type='text'></input>

But that sends the as-typed value back in the form data, so use either of the following to store it as all-caps in the database:

MySQL: UPPER(str)

PHP: strtoupper()

Chetan
An added advantage to this method is that the user only sees all-caps text being entered, and doesn't have to watch his / her typed text turn into upper-case, as with using the Javascript method.
Chetan
+1, the true-value could also be converted to uppercase in the onsubmit event of the form, before the data is sent to the server.
Andy E
+1, better answer than mine. I didn't know about this text-transform option, is it fully cross-browser?
Rob Van Dam
We can use this plus an on blur uppercase method to work around. $("#test").css('text-transform','uppercase').blur(function(){ this.value = this.value.toUpperCase(); });
jackysee
A: 

Another solution, if you use the text-transform: uppercase; css property:

<input id='test' style='text-transform: uppercase;' type='text'></input>

And with jQuery help you choose the blur event:

$("#test").blur(function(){ this.value = this.value.toUpperCase(); });

With this solution, you don't have to upper the database fields. You can use cursors to movement and do rewrite or insert in the input field.