Convert to uppercase as user types using javascript

后端 未结 12 1567
清酒与你
清酒与你 2020-12-13 17:59

I want to convert lowercase chars to uppercase as the user types using javascript. Any suggestions are welcome.

I have tried the following:

$(\"#text         


        
12条回答
  •  死守一世寂寞
    2020-12-13 18:35

    This is a solution I came up with, which also avoids the issues with placeholders changing to upper case, and does not mess around with the cursor position.

    Caution: does not change the "value" of the field, only the display. For that see here: Updating an input's value without losing cursor position

    $(function() {
        $("[data-uppercase='1']").on('keypress', function (e) {
            var $this = $(this);
            var placeholder = $this.attr('placeholder');
            if(placeholder && placeholder.length > 0) {
                this["_placeholder"] = placeholder;
                $this.attr('placeholder', '');
            }
            $this.css('text-transform', 'uppercase');
        }).on('keyup blur', function () {
            var $this = $(this);
            if ($this.val().length < 1) {
                $this.css("text-transform", "");
                $this.attr("placeholder", this["_placeholder"]);
                this["_placeholder"] = undefined;
            }
        });
    });
    

    Then add a data-uppercase attribute to the HTML element:

    
    

    Worked in Chrome, Firefox and IE9+.

    Fiddle: https://jsfiddle.net/GarryPas/ptez7q0q/3/

提交回复
热议问题