My goal is to use the jQuery event .keyup() to convert inputted lowercase chars to uppercase.
How can I achieve this?
As placeholder text is becoming more commonly supported, this update may be relevant.
My issue with the other answers is that applying the text-transform: uppercase
css would also uppercase the placeholder text, which we didn't want.
To work around this, it was a little tricky but worth the net effect.
Create the text-uppercase class.
.text-uppercase {
text-transform:uppercase;
}
Bind to the keydown event.
Binding to the keydown event was important to get the class to be added before the character was visible. Binding to keypress or keyup left the brief flicker of the lowercase letter.
$('input').on('keydown', function(e)
{
// Visually Friendly Auto-Uppercase
var $this = $(this);
// 1. Length of 1, hitting backspace, remove class.
if ($this.val().length == 1 && e.which == 8)
{
$this.removeClass('text-uppercase');
}
// 2. Length of 0, hitting character, add class.
if ($this.val().length == 0 && e.which >= 65 && e.which <= 90)
{
$this.addClass('text-uppercase');
}
});
Transform to uppercase when submitting to server.
var myValue = this.value.toUpperCase();
YMMV, you may find that cutting text or deleting text with the delete key may not remove the class. You can modify the keydown to also take the delete character into account.
Also, if you only have one character, and your current cursor position is in position 0, hitting backspace will remove the text-transform class, but since the cursor position is in position 0, it doesn't delete the single character.
This would require a bit more work to also check the current character position and determine if the delete or backspace key will actually delete the single remaining character.
Although it was worth the extra effort to make this seemless and visually appealing for our most common use case, going beyond this wasn't necessary. :)