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

后端 未结 21 2480
爱一瞬间的悲伤
爱一瞬间的悲伤 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 16:47

    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.

    JQuery plugin combined from some of the techniques mentioned earlier, plus it capitalizes words after hyphens, i.e.: "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();
    

提交回复
热议问题