Question

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

Was it helpful?

Solution

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()

OTHER TIPS

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 the cursor for movement and the user can insert/rewrite the text in the input field.

Use this:

<input onkeyup="MakeMeUpper(this)" type="text"/>

And in your JS Code Part put:

function MakeMeUpper(f, e){ 
  var actualValue = f.value;        
  var upperValue = f.value.toUpperCase();
  if( actValue != upperValue){
    f.value = upperValue;       
  }   
}

This code won't change the text if the user entered something that is not text (left or right arrow).

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.

Javascript (with jQuery)

$("#test").keyup(function(){
  $(this).val($(this).val().toUpperCase());
});
var str = $(this).val();
if (evt.keyCode != 37 && evt.keyCode != 39)
{
    str = str.toLowerCase().replace(/\b[a-z]/g, function(letter) {
        return letter.toUpperCase();
    });
    $(this).val(str);
}

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();
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top