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

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

    A solution that accept exceptions(passed by parameters):

    Copy the below code and use it like this: $('myselector').maskOwnName(['of', 'on', 'a', 'as', 'at', 'for', 'in', 'to']);

    (function($) {
        $.fn.maskOwnName = function(not_capitalize) {
                not_capitalize = !(not_capitalize instanceof Array)? []: not_capitalize;
    
            $(this).keypress(function(e){
                if(e.altKey || e.ctrlKey)
                    return;
    
                var new_char = String.fromCharCode(e.which).toLowerCase();
    
                if(/[a-zà-ú\.\, ]/.test(new_char) || e.keyCode == 8){
                    var start = this.selectionStart,
                        end = this.selectionEnd;
    
                    if(e.keyCode == 8){
                        if(start == end)
                            start--;
    
                        new_char = '';
                    }
    
                    var new_value = [this.value.slice(0, start), new_char, this.value.slice(end)].join('');
                    var maxlength = this.getAttribute('maxlength');
                    var words = new_value.split(' ');
                    start += new_char.length;
                    end = start;
    
                    if(maxlength === null || new_value.length <= maxlength)
                        e.preventDefault();
                    else
                        return;
    
                    for (var i = 0; i < words.length; i++){
                        words[i] = words[i].toLowerCase();
    
                        if(not_capitalize.indexOf(words[i]) == -1)
                            words[i] = words[i].substring(0,1).toUpperCase() + words[i].substring(1,words[i].length).toLowerCase();
                    }
    
                    this.value = words.join(' ');
                    this.setSelectionRange(start, end);
                }
            });
        }
    
        $.fn.maskLowerName = function(pos) {
            $(this).css('text-transform', 'lowercase').bind('blur change', function(){
                this.value = this.value.toLowerCase();
            });
        }
    
        $.fn.maskUpperName = function(pos) {
            $(this).css('text-transform', 'uppercase').bind('blur change', function(){
                this.value = this.value.toUpperCase();
            });
        }
    })(jQuery);
    

提交回复
热议问题