Capitalize first character of user input in real time with JQuery

后端 未结 8 1240
-上瘾入骨i
-上瘾入骨i 2021-02-14 13:15

I am trying to auto-capitalize the first character of a textarea/input that the user inputs. The first attempt looked like this:

$(document).ready(function() {
         


        
相关标签:
8条回答
  • 2021-02-14 14:06

    Here is a fiddle I made that does what you want in Chrome. I'm not sure if it will work in other browsers.

    Code:

    $(document).ready(function() {
        $('input').on('keydown', function(event) {
            if (this.selectionStart == 0 && event.keyCode >= 65 && event.keyCode <= 90 && !(event.shiftKey) && !(event.ctrlKey) && !(event.metaKey) && !(event.altKey)) {
               var $t = $(this);
               event.preventDefault();
               var char = String.fromCharCode(event.keyCode);
               $t.val(char + $t.val().slice(this.selectionEnd));
               this.setSelectionRange(1,1);
            }
        });
    });
    
    0 讨论(0)
  • 2021-02-14 14:11

    It would be much easier to use CSS in this case:

    input{
        text-transform: capitalize;
    }
    

    Update: this works when you don't want to capitalize the first letter of every word, but only the first letter of the first word:

    input::first-letter{
        text-transform: uppercase;
    }
    
    0 讨论(0)
提交回复
热议问题