将文本输入大写的 JavaScript 代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9576486/
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-10-26 07:06:07  来源:igfitidea点击:

JavaScript Code to Capitalize Text Inputs

javascriptjquerygreasemonkeycapitalizationcapitalize

提问by henryaaron

I'm using the popular Firefox extension Greasemonkey.

我正在使用流行的 Firefox 扩展Greasemonkey

I'd like to know if there was a way to capitalize all text inputs in a certain form, so if I would use jQuery the code would look something like:

我想知道是否有办法以某种形式将所有文本输入大写,因此如果我使用 jQuery,代码将如下所示:

$('form#formid input[type=text]').capitalize();

Now of course I know .capitalize()is not a valid function, and in order to capitalize text you'd need a complicated JavaScript code, but after all the Googling, I could not find one that seemed like it could be implemented into Greasemonkey.

现在当然我知道.capitalize()这不是一个有效的函数,为了将文本大写,你需要一个复杂的 JavaScript 代码,但是在谷歌搜索之后,我找不到一个看起来可以在 Greasemonkey 中实现的代码。

Can anybody help me to write this script?

有人可以帮我写这个脚本吗?

By capitalize, I mean capitalizing the first letter of each word, like the CSS text-transform:capitalize;and it must override the letters the user might put in, maybe doing it on form submit would be easier...

大写,我的意思是将每个单词的第一个字母大写,就像 CSS 一样text-transform:capitalize;,它必须覆盖用户可能输入的字母,也许在表单提交上做会更容易......

Thanks.

谢谢。

回答by Jasper

//add a function to jQuery so we can call it on our jQuery collections
$.fn.capitalize = function () {

    //iterate through each of the elements passed in, `$.each()` is faster than `.each()
    $.each(this, function () {

        //split the value of this input by the spaces
        var split = this.value.split(' ');

        //iterate through each of the "words" and capitalize them
        for (var i = 0, len = split.length; i < len; i++) {
            split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1);
        }

        //re-join the string and set the value of the element
        this.value = split.join(' ');
    });
    return this;
};

Here is a demo: http://jsfiddle.net/jasper/qppGQ/1/

这是一个演示:http: //jsfiddle.net/jasper/qppGQ/1/

This could be used inside an event handler to always keep a capitalized body of text:

这可以在事件处理程序中使用以始终保持大写的文本正文:

//when the user presses a key and the value of the `textarea` is changed, the new value will have all capitalized words
$('textarea').on('keyup', function () {
    $(this).capitalize();
}).capitalize();//also capitalize the `textarea` element(s) on initialization

Here is a demo: http://jsfiddle.net/jasper/qppGQ/2/

这是一个演示:http: //jsfiddle.net/jasper/qppGQ/2/

Update

更新

To have the first letter be capitalized and the rest of the word be lowercase we can just use .toLowerCase()in the remainder of the string after capitalizing the first letter:

要将第一个字母大写而单词的其余部分小写,我们可以.toLowerCase()在将第一个字母大写后在字符串的其余部分使用:

        ...
        for (var i = 0, len = split.length; i < len; i++) {
            split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1).toLowerCase();
        }
        ...

Here is a demo: http://jsfiddle.net/jasper/qppGQ/3/

这是一个演示:http: //jsfiddle.net/jasper/qppGQ/3/

回答by Eli

Is this what you are trying to do?

这是你想要做的吗?

(function ($) {

    $.fn.capitalize = function () {
        return this.val(function (i, oldValue) {
            return oldValue.charAt(0).toUpperCase() + oldValue.slice(1);
        });
    };

})(jQuery);

If you wanted to perform this action in "realtime", you could just process the action inside of an event:

如果您想“实时”执行此操作,则只需在事件内部处理该操作:

(function ($) {

    $.fn.capitalize = function () {
        this.on('keyup.capitalize change.capitalize', function () { 
            $(this).val(function (i, oldValue) {
                return oldValue.charAt(0).toUpperCase() + oldValue.slice(1);
            });
        });
    };

})(jQuery);

回答by Matt Esch

My simple implementation of a capitalize function splits up a string by spaces and capitalizes the first letter of each word. It assumes each word is divided by at least one space.

我对大写函数的简单实现用空格分割了一个字符串,并将每个单词的第一个字母大写。它假设每个单词至少被一个空格分隔。

function capitalize(text) {
    var i, words, w, result = '';

    words = text.split(' ');

    for (i = 0; i < words.length; i += 1) {
        w = words[i];
        result += w.substr(0,1).toUpperCase() + w.substr(1);
        if (i < words.length - 1) {
            result += ' ';    // Add the spaces back in after splitting
        }
    }

    return result;
}

Example console output:

控制台输出示例:

> capitalize("some tEsT e strING a B c 1 2 3")
  "Some TEsT E StrING A B C 1 2 3"

回答by davidbii

I took the tips here and have formulated something a little easier using standard javascript. I needed to capitalize the each word of an input box on an iPad Web App, autocapitalize was failing to work consistently. Here's the work around:

我在这里接受了提示,并使用标准 javascript 制定了一些更容易的东西。我需要将 iPad 网络应用程序上输入框的每个单词大写,自动大写无法始终如一地工作。这是解决方法:

HTML Input

HTML 输入

<input type="text" id="this_input" name="this_input" onkeyup="javascript:capitalize(this.id, this.value);">

Javascript

Javascript

<script type="text/javascript">
  function capitalize(textboxid, text) {
      // string with alteast one character
      var i, words, w, result = '';

    words = text.split(' ');

    for (i = 0; i < words.length; i += 1) {
        w = words[i];
        result += w.substr(0,1).toUpperCase() + w.substr(1);
        if (i < words.length - 1) {
            result += ' ';    // Add the spaces back in after splitting
        }
    }
      document.getElementById(textboxid).value = result;
  }
  </script>

回答by fruchtose

You're going to want an event handler for the DOM object in question--specifically, the keypressevent handler. You'll need to read the text of the input field after each key press to ensure that all words (text surrounded by spaces) have the first character capitalized.

您将需要有问题的 DOM 对象的keypress事件处理程序——特别是事件处理程序。您需要在每次按下按键后阅读输入字段的文本,以确保所有单词(由空格包围的文本)的第一个字符都大写。

For instance:

例如:

$('form#formid input[type=text]').keypress(function(event) {
// Function body goes here
});

As a general strategy, I recommend splitting the value of the input field by spaces (using str.split(" ");). Then, iterate through each of the resulting strings. For each string, slice off everything after the first letter, and append a capitalized first character to the sliced string. You can see other answers show you how to do this. Combine all these strings into one and set the value of the input to this capitalized string.

作为一般策略,我建议按空格拆分输入字段的值(使用str.split(" ");)。然后,遍历每个结果字符串。对于每个字符串,切掉第一个字母之后的所有内容,并将大写的第一个字符附加到切好的字符串。您可以看到其他答案向您展示了如何执行此操作。将所有这些字符串合并为一个,并将输入的值设置为这个大写的字符串。

回答by charlietfl

version with event binding built in

内置事件绑定的版本

Simpl use

简单使用

$('input[type="text"]').capitalize()

http://jsfiddle.net/uUjgg/

http://jsfiddle.net/uUjgg/

(function($) {

$.fn.capitalize = function() {
    return this.each(function() {
        var $field = $(this);

        $field.on('keyup change', function() {
            $field.val(function(i, old) {
                if (old.indexOf(' ') > -1) {
                    var words = old.split(' ');
                    for (i = 0; i < words.length; i++) {
                        words[i] = caps(words[i]);
                    }
                    return words.join(' ');
                } else {
                    return caps(old);
                }
            });
        });
    });

    function caps(str) {
        return str.charAt(0).toUpperCase() + str.slice(1);
    }
};

})(jQuery);