Javascript 使用 jQuery,如何在用户仍在编辑该字段时将文本字段的第一个字母大写?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2017456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:25:15  来源:igfitidea点击:

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

javascriptjquerycapitalization

提问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 stilltyping.

我正在寻找一个示例,说明如何将输入到文本字段中的字符串的第一个字母大写。通常,这是使用函数、正则表达式OnBlurOnChange、 等在整个字段上完成的。我想在用户仍在键入时将第一个字母大写。

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.

例如,如果我输入“cat”这个词,用户应该按“c”,然后当他按“a”时,C 应该在字段中大写。

I think what I'm going for might be possible with keyupor keypressbut I'm not sure where to start.

我认为我的目标可能是keyup或者keypress但我不确定从哪里开始。

Anyone have an example for me?

有人有我的例子吗?

回答by NotMe

Just use CSS.

只需使用 CSS。

.myclass 
{
    text-transform:capitalize;
}

回答by Zee

This will simply transform you first letter of text:

这将简单地转换您文本的第一个字母:

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

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

回答by sakhunzai

I answered this somewhere else . However, here are two function you might want to call on keyup event.

我在别处回答了这个问题。但是,这里有两个您可能想要在 keyup 事件上调用的函数。

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

正如@Darrell 建议的那样

$('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 :)

干杯:)

回答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(){ return .toUpperCase( ); }));
});

回答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.

带有“文本转换:大写;”的 CSS 解决方案 如果您想在后端使用输入的内容,那就不好了。您仍将按原样接收数据。JavaScript 解决了这个问题。

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

JQuery 插件结合了前面提到的一些技术,加上连字符后的单词大写,即:“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();

回答by cumul

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

我使用了@Spajus 的代码并编写了一个更扩展的jQuery 插件。

I wrote these four jQuery functions:

我写了这四个 jQuery 函数:

  • 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
  • upperFirstAll()将输入字段中的所有单词大写
  • upperFirst()只大写第一个单词
  • upperCase()将孔文本转换为大写
  • lowerCase()将孔文本转换为小写

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

您可以像任何其他 jQuery 函数一样使用和链接它们:
$('#firstname').upperFirstAll()

My complete jQuery plugin:

我完整的 jQuery 插件:

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

格罗耶斯 :)

回答by Todd

My personal favorite when using jQuery is short and sweet:

我个人在使用 jQuery 时最喜欢的是简短而甜蜜的:

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

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

有一个 jQuery 插件也可以做到这一点。我会称它为... jCap.js

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

回答by István

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

回答by Aaron Hopkins

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

对上面的代码稍作更新,强制字符串在首字母大写之前降低。

(Both use Jquery syntax)

(均使用 Jquery 语法)

    function CapitaliseFirstLetter(elemId) {
        var txt = $("#" + elemId).val().toLowerCase();
        $("#" + elemId).val(txt.replace(/^(.)|\s(.)/g, function() {
        return .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"

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

希望这可以帮助。快乐编码!:)