Convert to uppercase as user types using javascript

后端 未结 12 1558
清酒与你
清酒与你 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:42

    I know I'm quite late to the party, but I'd like to offer this:

    (function ( $ ) {
    
      var displayUppercase = function ($element) {
        if ($element.val()) {
          $element.css('text-transform', 'uppercase');
        } else {
          $element.css('text-transform', 'none');
        }
      };
    
      $.fn.displayAsUppercase = function() {
        $(this).each(function() {
            var $element = $(this);
          displayUppercase($element);
          $element.on('input', function(){displayUppercase($element)});
        });
        return this;
        };
    
    }( jQuery ));
    

    It has these advantages:

    • Keeps the placeholder capitalization intact
    • Capitalizes the input immediately (on keydown)
    • Doesn't move the cursor
    • Capitalizes the value of the input if it's prepopulated

    JS Fiddle here

提交回复
热议问题