6

I'm using the popular Firefox extension 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:

$('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.

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

Thanks.

4

6 に答える 6

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

ここにデモがあります: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

ここにデモがあります: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();
        }
        ...

ここにデモがあります:http://jsfiddle.net/jasper/qppGQ/3/

于 2012-03-06T01:20:23.110 に答える
4

これはあなたがやろうとしていることですか?

(function ($) {

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

})(jQuery);

このアクションを「リアルタイム」で実行したい場合は、イベント内でアクションを処理できます。

(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);
于 2012-03-06T01:15:45.337 に答える
1

capitalize 関数の単純な実装では、文字列をスペースで分割し、各単語の最初の文字を大文字にします。各単語が少なくとも 1 つのスペースで区切られていることを前提としています。

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

コンソール出力の例:

> capitalize("some tEsT e strING a B c 1 2 3")
  "Some TEsT E StrING A B C 1 2 3"
于 2012-03-06T01:19:53.060 に答える
1

ここでのヒントを参考にして、標準の JavaScript を使用してもう少し簡単に作成しました。iPad Web アプリの入力ボックスの各単語を大文字にする必要がありましたが、自動大文字化が一貫して機能しませんでした。回避策は次のとおりです。

HTML 入力

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

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>
于 2015-02-13T21:06:51.247 に答える
0

イベントバインディングが組み込まれたバージョン

簡単な使用

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

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);
于 2012-03-06T01:35:38.397 に答える
0

問題の DOM オブジェクトのイベント ハンドラー、具体的にはkeypressイベント ハンドラーが必要になります。キーを押すたびに入力フィールドのテキストを読み、すべての単語 (スペースで囲まれたテキスト) の最初の文字が大文字になっていることを確認する必要があります。

例えば:

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

一般的な戦略として、入力フィールドの値をスペースで分割することをお勧めします ( を使用str.split(" ");)。次に、結果の各文字列を反復処理します。文字列ごとに、最初の文字以降をすべて切り取り、切り出した文字列に大文字の最初の文字を追加します。他の回答がこれを行う方法を示しているのを見ることができます。これらすべての文字列を 1 つに結合し、入力の値をこの大文字の文字列に設定します。

于 2012-03-06T01:19:37.753 に答える