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

后端 未结 21 2501
爱一瞬间的悲伤
爱一瞬间的悲伤 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 17:02

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

提交回复
热议问题