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

后端 未结 21 2354
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-27 16:26

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

相关标签:
21条回答
  • 2020-11-27 16:48

    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

    0 讨论(0)
  • 2020-11-27 16:50
    $('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 讨论(0)
  • 2020-11-27 16:50

    If using Bootstrap, add:

    class="text-capitalize"
    

    For example:

    <input type="text" class="form-control text-capitalize" placeholder="Full Name" value="">
    
    0 讨论(0)
  • 2020-11-27 16:51

    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();
        }));
    });
    
    0 讨论(0)
  • 2020-11-27 16:52

    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 讨论(0)
  • 2020-11-27 16:52

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

    0 讨论(0)
提交回复
热议问题