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

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

    My attempt.

    Only acts if all text is lowercase or all uppercase, uses Locale case conversion. Attempts to respect intentional case difference or a ' or " in names. Happens on Blur as to not cause annoyances on phones. Although left in selection start/end so if changed to keyup maybe useful still. Should work on phones but have not tried.

    $.fn.capitalize = function() {
        $(this).blur(function(event) {
            var box = event.target;
            var txt = $(this).val();
            var lc = txt.toLocaleLowerCase();
            var startingWithLowerCaseLetterRegex = new RegExp("\b([a-z])", "g");
            if (!/([-'"])/.test(txt) && txt === lc || txt === txt.toLocaleUpperCase()) {
                var stringStart = box.selectionStart;
                var stringEnd = box.selectionEnd;
                $(this).val(lc.replace(startingWithLowerCaseLetterRegex, function(c) { return c.toLocaleUpperCase() }).trim());
                box.setSelectionRange(stringStart, stringEnd);
            }
        });
       return this;
    }
    
    // Usage:
    $('input[type=text].capitalize').capitalize();
    

提交回复
热议问题