Capitalize first character of user input in real time with JQuery

后端 未结 8 1216
-上瘾入骨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 13:51

    You can use a jQuery function:

    $.fn.CapitalizeFirst = function () {
        return this.each(function () {
            $(this).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 13:53

    Working jQuery. Make sure you write the code below after importing jQuery:

    <script type="text/javascript" charset="utf-8">
    jQuery(document).ready(function($) {
        $('#id_of_input').keyup(function(event) {
            var textBox = event.target;
            var start = textBox.selectionStart;
            var end = textBox.selectionEnd;
            textBox.value = textBox.value.charAt(0).toUpperCase() + textBox.value.slice(1);
            textBox.setSelectionRange(start, end);
        });
    });
    </script>
    
    0 讨论(0)
  • 2021-02-14 13:55

    This was discussed in a previous thread. How do I make the first letter of a string uppercase in JavaScript?

    You could just grab the users input after the first word is typed or really whenever you want and reset the value using the methods discussed in the link above.

    0 讨论(0)
  • 2021-02-14 13:57
    $('selector').blur(function(){
            $(this).val($(this).val().charAt(0).toUpperCase()+$(this).val().slice(1)); 
      });
    
    0 讨论(0)
  • 2021-02-14 14:04

    This works for me.

    $('input').keyup(function() {
      $(this).val($(this).val().substr(0, 1).toUpperCase() + $(this).val().substr(1).toLowerCase());
    });
    
    0 讨论(0)
  • 2021-02-14 14:04

    Try this:

    $(document).ready(function() {
        $('input').on('keydown', function(e) {
            if (this.value == '') {
            var char = String.fromCharCode(e.which);
                if (char.match(/^\w$/)) {
                    // If is empty and we pressed a printable key...
                    this.value = char.toUpperCase();
                    return false;
                }
            }
        });
    });
    

    See in use here.

    0 讨论(0)
提交回复
热议问题