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, r
My attempt.
Only acts if all text is lowercase or all uppercase, uses Locale case conversion. Attempts to respect intentional case difference or a ' or " in names. Happens on Blur as to not cause annoyances on phones. Although left in selection start/end so if changed to keyup maybe useful still. Should work on phones but have not tried.
$.fn.capitalize = function() {
$(this).blur(function(event) {
var box = event.target;
var txt = $(this).val();
var lc = txt.toLocaleLowerCase();
var startingWithLowerCaseLetterRegex = new RegExp("\b([a-z])", "g");
if (!/([-'"])/.test(txt) && txt === lc || txt === txt.toLocaleUpperCase()) {
var stringStart = box.selectionStart;
var stringEnd = box.selectionEnd;
$(this).val(lc.replace(startingWithLowerCaseLetterRegex, function(c) { return c.toLocaleUpperCase() }).trim());
box.setSelectionRange(stringStart, stringEnd);
}
});
return this;
}
// Usage:
$('input[type=text].capitalize').capitalize();
Slight update to cumul's solution.
The function upperFirstAll doesn't work properly if there is more than one space between words. Replace the regular expression for this one to solve it:
$(this).val(txt.toLowerCase().replace(/^(.)|(\s|\-)+(.)/g,
I answered this somewhere else . However, here are two function you might want to call on keyup event.
To capitalize first word
function ucfirst(str,force){
str=force ? str.toLowerCase() : str;
return str.replace(/(\b)([a-zA-Z])/,
function(firstLetter){
return firstLetter.toUpperCase();
});
}
And to capitalize all words
function ucwords(str,force){
str=force ? str.toLowerCase() : str;
return str.replace(/(\b)([a-zA-Z])/g,
function(firstLetter){
return firstLetter.toUpperCase();
});
}
As @Darrell Suggested
$('input[type="text"]').keyup(function(evt){
// force: true to lower case all letter except first
var cp_value= ucfirst($(this).val(),true) ;
// to capitalize all words
//var cp_value= ucwords($(this).val(),true) ;
$(this).val(cp_value );
});
Hope this is helpful
Cheers :)
.first-character{
font-weight:bold;
color:#F00;
text-transform:capitalize;
}
.capital-text{
text-transform:uppercase;
}
This will simply transform you first letter of text:
yourtext.substr(0,1).toUpperCase()+yourtext.substr(1);
With Javascript you can use:
yourtext.substr(0,1).toUpperCase()+yourtext.substr(1);
If by chance you're generating your web page with PHP you can also use:
<?=ucfirst($your_text)?>