JavaScript
Article

Capitalize First Letter of Every Word on Keypress

By Sam Deering

jQuery code snippet to make capitals of the first letter of every word in the string. This could be used to prevent users from entering all caps for titles or text when they input data into forms.

//usage
$(“input”).keyup(function() {
toUpper(this);
});

//function
function toUpper(obj) {
var mystring = obj.value;
var sp = mystring.split(‘ ‘);
var wl=0;
var f ,r;
var word = new Array();
for (i = 0 ; i < sp.length ; i ++ ) { f = sp[i].substring(0,1).toUpperCase(); r = sp[i].substring(1).toLowerCase(); word[i] = f+r; } newstring = word.join(' '); obj.value = newstring; return true; } [/js]

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

  • Orlando

    Good Job, but this script ignore input password?

  • Adam G.

    Hi!

    While searching for some good example for the problem, I found yours. And then used it for a moment, but found a problem, with capitalizing words after hyphens. And thought about regex in JS. So, after few attempts and some searching on JS regex replace, got this:

    function upCaseWords(mystring) {
    regex = /(^|s|-)./g
    return mystring.replace(regex, function (v) {return v.toUpperCase();});
    }

    This function upcases letters on all words: at the beginning of a sentence, after each space, and hyphens. Of course you can add any other symbol being a separator. :)

    Good luck! :)

  • Pankaj Garg

    Adam G pls tell me how can i add this for keyup event in an input filed.

  • Pankaj Garg

    Sam Deering
    this function works fine for me but in input filed when we finish typing cursor can’t move from end to start. how to solve this.

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.