How to change lowercase chars to uppercase using the 'keyup' event?

后端 未结 12 1822
失恋的感觉
失恋的感觉 2021-01-31 01:58

My goal is to use the jQuery event .keyup() to convert inputted lowercase chars to uppercase.

How can I achieve this?

12条回答
  •  伪装坚强ぢ
    2021-01-31 02:25

    Solution 1 (Elegant approach with great user experience)

    HTML

    
    

    CSS

    .uppercase{
        text-transform: uppercase;
    }
    

    JS

    $('#inputID').on('blur', function(){
        this.value = this.value.toUpperCase();
    });
    

    By using CSS text-transform: uppercase; you'll eliminate the animation of lower to uppercase as the user types into the field.

    Use blur event to handle converting to uppercase. This happens behind the scene as CSS took care of the user's visually appealing masking.

    Solution 2 (Great, but less elegant)

    If you insist on using keyup, here it is...

    $('#inputID').on('keyup', function(){
        var caretPos = this.selectionStart;
        this.value = this.value.toUpperCase();
        this.setSelectionRange(caretPos, caretPos);
    });
    

    User would notice the animation of lowercase to uppercase as they type into the field. It gets the job done.

    Solution 3 (Just get the job done)

    $('#inputID').on('keyup', function(){
        this.value = this.value.toUpperCase();
    });
    

    This method is most commonly suggested but I do not recommend.

    The downside of this solution is you'll be annoying the user as the cursor's caret position keeps jumping to the end of the text after every key input. Unless you know your users will never encounter typos or they will always clear the text and retype every single time, this method works.

提交回复
热议问题