用于大写文本输入的JavaScript代码

hen*_*ron 6 javascript jquery greasemonkey capitalize capitalization

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

我想知道是否有办法以某种形式大写所有文本输入,所以如果我使用jQuery代码看起来像:

$('form#formid input[type=text]').capitalize();
Run Code Online (Sandbox Code Playgroud)

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

任何人都可以帮我写这个脚本吗?

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

谢谢.

Jas*_*per 10

//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;
};
Run Code Online (Sandbox Code Playgroud)

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

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

//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
Run Code Online (Sandbox Code Playgroud)

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

更新

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

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

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