views:

2903

answers:

4

I'm looking for an example of how to capitalize the first letter of a string being entered into a text field. Normally, this is done on the entire field with a function or regex onBlur or OnChange, etc... I want to capitalize the first letter while the user is STILL typing.

For instance, if I'm typing the word "cat" -- The user should press 'c', then by the time he presses 'a', the C should be capitalized in the field.

I think what I'm going for might be possible with keyup or keypress but I'm not sure where to start.

Anyone have an example for me?

+2  A: 
$('input[type="text"]').keyup(function(evt){
    var txt = $(this).val();


    // Regex taken from php.js (http://phpjs.org/functions/ucwords:569)
    $(this).val(txt.(str+'').replace(/^(.)|\s(.)/g, function($1){ return $1.toUpperCase( ); }));
});
Darrell Brogdon
+3  A: 

Just use CSS.

.myclass 
{
    text-transform:capitalize;
}
Chris Lively
This will capitalize EVERY word.
Kaleb Brasee
@Kaleb The 'capitalize' value capitalizes the first character of each word. http://www.w3schools.com/Css/pr_text_text-transform.asp
Darrell Brogdon
Yeah that's what I mean, the OP only wants to capitalize the first word of the entire field.
Kaleb Brasee
seriously what is OP?
Anurag
@Anurag: OP = Original Poster. In this case tresstylez.
Chris Lively
@Kaleb: Are you sure? The only example given was for the word "cat"
Chris Lively
Although this doesn't help the OP since it doesn't affect form fields the :first-letter pseudo-element will only affect the first letter of a block of text.
Graham
This was simple and worked great. I type the first letter and there was no delay in the capitalization in FF and only a miniscule delay in IE, as if I had CAPS LOCK on for the first letter. Thanks Chris.
tresstylez
A: 
Anurag
What about when the user goes back to edit the start of an input?
Tim Down
@Tim That wouldn't happen because the user won't be able to go back. As the entire value is changed on `keyup` and cursor goes right to the end. But I have added the fix that takes care of allowing the user to move around the box and change anything.
Anurag
A: 

I am trying to use the function mentioned below ($('#up').keyup(function(event) { var textBox = event.target; ...) and something weird is happening with the usage combination Greek+Google Chrome. It capitalizes the first char but also replaces it with some other char. I am using currently using Google Chrome 5.0.375.70. Any ideas?

np0