With jQuery, how do I capitalize the first letter of a text field while the user is still editing that field?

JavascriptJqueryCapitalization

Javascript Problem Overview


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, regex, OnBlur, 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', and 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?

Javascript Solutions


Solution 1 - Javascript

Just use CSS.

.myclass 
{
	text-transform:capitalize;
}

Solution 2 - Javascript

This will simply transform you first letter of text:

yourtext.substr(0,1).toUpperCase()+yourtext.substr(1);

Solution 3 - Javascript

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

Solution 4 - Javascript

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


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

Solution 5 - Javascript

CSS solution with "text-transform: capitalize;" is no good if you want to use the contents of the input in backend. You will still receive data as-is. JavaScript solves this issue.

JQuery plugin combined from some of the techniques mentioned earlier, plus it capitalizes words after hyphens, i.e.: "Tro Lo-Lo":

Add to your script:

jQuery.fn.capitalize = function() {
    $(this[0]).keyup(function(event) {
        var box = event.target;
        var txt = $(this).val();
        var stringStart = box.selectionStart;
        var stringEnd = box.selectionEnd;
        $(this).val(txt.replace(/^(.)|(\s|\-)(.)/g, function($word) {
            return $word.toUpperCase();
        }));
        box.setSelectionRange(stringStart , stringEnd);
    });

   return this;
}

Then just attach capitalize() to any selector:

$('#myform input').capitalize();

Solution 6 - Javascript

I used the code of @Spajus and wrote a more extended jQuery plugin.

I wrote these four jQuery functions:

  • upperFirstAll() to capitalize ALL words in an inputfield
  • upperFirst() to capitalize only the FIRST word
  • upperCase() to convert the hole text to upper case
  • lowerCase() to convert the hole text to lower case

You can use and chain them like any other jQuery function:
$('#firstname').upperFirstAll()

My complete jQuery plugin:

(function ($) {
    $.fn.extend({
    
    // With every keystroke capitalize first letter of ALL words in the text
    upperFirstAll: function() {
        $(this).keyup(function(event) {
            var box = event.target;
            var txt = $(this).val();
            var start = box.selectionStart;
            var end = box.selectionEnd;
            
            $(this).val(txt.toLowerCase().replace(/^(.)|(\s|\-)(.)/g,
            function(c) {
                return c.toUpperCase();
            }));
            box.setSelectionRange(start, end);
        });
        return this;
    },
    
    // With every keystroke capitalize first letter of the FIRST word in the text
    upperFirst: function() {
        $(this).keyup(function(event) {
            var box = event.target;
            var txt = $(this).val();
            var start = box.selectionStart;
            var end = box.selectionEnd;
            
            $(this).val(txt.toLowerCase().replace(/^(.)/g,
            function(c) {
                return c.toUpperCase();
            }));
            box.setSelectionRange(start, end);
        });
        return this;
    },
    
    // Converts with every keystroke the hole text to lowercase
    lowerCase: function() {
        $(this).keyup(function(event) {
            var box = event.target;
            var txt = $(this).val();
            var start = box.selectionStart;
            var end = box.selectionEnd;
            
            $(this).val(txt.toLowerCase());
            box.setSelectionRange(start, end);
        });
        return this;
    },
    
    // Converts with every keystroke the hole text to uppercase
    upperCase: function() {
        $(this).keyup(function(event) {
            var box = event.target;
            var txt = $(this).val();
            var start = box.selectionStart;
            var end = box.selectionEnd;
            
            $(this).val(txt.toUpperCase());
            box.setSelectionRange(start, end);
        });
        return this;
    }

    });
}(jQuery));

Groetjes :)

Solution 7 - Javascript

My personal favorite when using jQuery is short and sweet:

function capitalize(word) {
   return $.camelCase("-" + word);
}

There's a jQuery plugin that does this too. I'll call it... jCap.js

$.fn.extend($, { 
    capitalize: function() {
        return $.camelCase("-"+arguments[0]); 
    } 
});

Solution 8 - Javascript

 $("#test").keyup(
     function () {
         this.value = this.value.substr(0, 1).toUpperCase() + this.value.substr(1).toLowerCase();
     }
 );

Solution 9 - Javascript

Slight update to the code above to force the string to lower before Capitaliing the first letter.

(Both use Jquery syntax)

    function CapitaliseFirstLetter(elemId) {
        var txt = $("#" + elemId).val().toLowerCase();
        $("#" + elemId).val(txt.replace(/^(.)|\s(.)/g, function($1) {
        return $1.toUpperCase(); }));
        }

In addition a function to Capitalise the WHOLE string:

    function CapitaliseAllText(elemId) {
         var txt = $("#" + elemId).val();
         $("#" + elemId).val(txt.toUpperCase());
         }

Syntax to use on a textbox's click event:

    onClick="CapitaliseFirstLetter('myTextboxId'); return false"

Solution 10 - Javascript

this will help you in - convert first letter of each word to uppercase

<script>
  /* convert First Letter UpperCase */
  $('#txtField').on('keyup', function (e) {
    var txt = $(this).val();
    $(this).val(txt.replace(/^(.)|\s(.)/g, function ($1) {
      return $1.toUpperCase( );
    }));
  });
</script>

Example : this is a title case sentence -> This Is A Title Case Sentence

Solution 11 - Javascript

My appologies. The syntax was off due to me being in a hurry and sloppy. Here you go...

     $('#tester').live("keyup", function (evt)
        {
            var txt = $(this).val();
            txt = txt.substring(0, 1).toUpperCase() + txt.substring(1);
            $(this).val(txt);
        });

Simple but works. You would def want to make this more general and plug and playable. This is just to offer another idea, with less code. My philosophy with coding, is making it as general as possible, and with as less code as possible.

Hope this helps. Happy coding! :)

Solution 12 - Javascript

It's very cool you can capitalize Only the first letter of an input field With this one.. If any one know how to capitalize Like CSS text-transform:capitalize, Please Reply .. Here You go..

$('input-field').keyup(function(event) { $(this).val(($(this).val().substr(0,1).toUpperCase())+($(this).val().substr(1))); });

Solution 13 - Javascript

A turkish one. If someone is still interested.

 $('input[type="text"]').keyup(function() {
    $(this).val($(this).val().replace(/^([a-zA-Z\s\ö\ç\ş\ı\i\ğ\ü\Ö\Ç\Ş\İ\Ğ\Ü])|\s+([a-zA-Z\s\ö\ç\ş\ı\i\ğ\ü\Ö\Ç\Ş\İ\Ğ\Ü])/g, function ($1) {
        if ($1 == "i")
            return "İ";
        else if ($1 == " i")
            return " İ";
        return $1.toUpperCase();
    }));
});

Solution 14 - Javascript

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

Solution 15 - Javascript

A solution that accept exceptions(passed by parameters):

Copy the below code and use it like this: $('myselector').maskOwnName(['of', 'on', 'a', 'as', 'at', 'for', 'in', 'to']);

(function($) {
    $.fn.maskOwnName = function(not_capitalize) {
            not_capitalize = !(not_capitalize instanceof Array)? []: not_capitalize;

        $(this).keypress(function(e){
            if(e.altKey || e.ctrlKey)
                return;

            var new_char = String.fromCharCode(e.which).toLowerCase();

            if(/[a-zà-ú\.\, ]/.test(new_char) || e.keyCode == 8){
                var start = this.selectionStart,
                    end = this.selectionEnd;

                if(e.keyCode == 8){
                    if(start == end)
                        start--;

                    new_char = '';
                }

                var new_value = [this.value.slice(0, start), new_char, this.value.slice(end)].join('');
                var maxlength = this.getAttribute('maxlength');
                var words = new_value.split(' ');
                start += new_char.length;
                end = start;

                if(maxlength === null || new_value.length <= maxlength)
                    e.preventDefault();
                else
                    return;

                for (var i = 0; i < words.length; i++){
                    words[i] = words[i].toLowerCase();

                    if(not_capitalize.indexOf(words[i]) == -1)
                        words[i] = words[i].substring(0,1).toUpperCase() + words[i].substring(1,words[i].length).toLowerCase();
                }

                this.value = words.join(' ');
                this.setSelectionRange(start, end);
            }
        });
    }

    $.fn.maskLowerName = function(pos) {
        $(this).css('text-transform', 'lowercase').bind('blur change', function(){
            this.value = this.value.toLowerCase();
        });
    }

    $.fn.maskUpperName = function(pos) {
        $(this).css('text-transform', 'uppercase').bind('blur change', function(){
            this.value = this.value.toUpperCase();
        });
    }
})(jQuery);

Solution 16 - Javascript

Jquery or Javascipt doesn't provide a built-in method to achieve this.

CSS test transform (text-transform:capitalize;) doesn't really capitalize the string's data but shows a capitalized rendering on the screen.

If you are looking for a more legit way of achieving this in the data level using plain vanillaJS, use this solution =>

var capitalizeString = function (word) {    
    word = word.toLowerCase();
    if (word.indexOf(" ") != -1) { // passed param contains 1 + words
        word = word.replace(/\s/g, "--");
        var result = $.camelCase("-" + word);
        return result.replace(/-/g, " ");
    } else {
    return $.camelCase("-" + word);
    }
}

Solution 17 - Javascript

I use both CSS and jQuery solutions when achieving this. This will change both how it appears in the browser and the data value. A simple solution, that just works.

CSS

#field {
    text-transform: capitalize;
}

jQuery

$('#field').keyup(function() {
	var caps = jQuery('#field').val(); 
	caps = caps.charAt(0).toUpperCase() + caps.slice(1);
    jQuery('#field').val(caps);
});

Solution 18 - Javascript

If using Bootstrap, add:

class="text-capitalize"

For example:

<input type="text" class="form-control text-capitalize" placeholder="Full Name" value="">

Solution 19 - Javascript

    .first-character{
		font-weight:bold;
		color:#F00;
		text-transform:capitalize;
   }
.capital-text{
	text-transform:uppercase;
    }

Solution 20 - Javascript

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

Solution 21 - Javascript

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,

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontresstylezView Question on Stackoverflow
Solution 1 - JavascriptNotMeView Answer on Stackoverflow
Solution 2 - JavascriptZeeView Answer on Stackoverflow
Solution 3 - JavascriptsakhunzaiView Answer on Stackoverflow
Solution 4 - JavascriptDarrell BrogdonView Answer on Stackoverflow
Solution 5 - JavascriptSpajusView Answer on Stackoverflow
Solution 6 - JavascriptcumulView Answer on Stackoverflow
Solution 7 - JavascriptToddView Answer on Stackoverflow
Solution 8 - JavascriptIstván View Answer on Stackoverflow
Solution 9 - JavascriptAaron HopkinsView Answer on Stackoverflow
Solution 10 - JavascriptIrshad KhanView Answer on Stackoverflow
Solution 11 - JavascriptRonnyView Answer on Stackoverflow
Solution 12 - JavascriptPraneeth NidarshanView Answer on Stackoverflow
Solution 13 - JavascriptGO.exeView Answer on Stackoverflow
Solution 14 - JavascriptelkolotfiView Answer on Stackoverflow
Solution 15 - JavascriptDoglasView Answer on Stackoverflow
Solution 16 - JavascriptsiwalikmView Answer on Stackoverflow
Solution 17 - JavascriptAaron LynchView Answer on Stackoverflow
Solution 18 - JavascriptLineDropView Answer on Stackoverflow
Solution 19 - Javascriptsnkhan120View Answer on Stackoverflow
Solution 20 - JavascriptLiam MitchellView Answer on Stackoverflow
Solution 21 - JavascriptJuanView Answer on Stackoverflow