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

0 votes
asked Jan 7, 2010 by tresstylez

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?

17 Answers

0 votes
answered Jan 7, 2010 by darrell-brogdon
$('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( ); }));
});
0 votes
answered Jan 7, 2010 by notme

Just use CSS.

.myclass 
{
    text-transform:capitalize;
}
0 votes
answered Jan 25, 2011 by spajus

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();
0 votes
answered Jan 30, 2011 by sakhunzai

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

0 votes
answered Jan 27, 2012 by aaron-hopkins

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"
0 votes
answered Jan 29, 2012 by zee

This will simply transform you first letter of text:

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

0 votes
answered Jan 9, 2013 by snkhan120
    .first-character{
        font-weight:bold;
        color:#F00;
        text-transform:capitalize;
   }
.capital-text{
    text-transform:uppercase;
    }
0 votes
answered Jan 14, 2013 by cumul

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

0 votes
answered Jan 14, 2013 by ronny

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

0 votes
answered Jan 10, 2014 by praneethn

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

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...