10

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() {
 $('input').on('keydown', function() {
    if (this.value[0] != this.value[0].toUpperCase()) {
        // store current positions in variables
        var start = this.selectionStart;
        var end = this.selectionEnd; 
        this.value = this.value[0].toUpperCase() + this.value.substring(1);
        // restore from variables...
        this.setSelectionRange(start, end);
    }
 });
});

The problem with this is that it shows the lowercase character and then corrects it, which is ugly (http://jsfiddle.net/9zPTA/2/). I would like to run my javascript on keydown instead of keyup, and transform the event in flight (or intercept it, prevent default, and trigger a modified new event).

Here's what I have now, which doesn't work (http://jsfiddle.net/9zPTA/5/):

$(document).ready(function() {
  $('input').on('keydown', function(event) {
    if (this.selectionStart == 0 && event.keyCode >= 65 && event.keyCode <= 90 && !(event.shiftKey)) {
       event.preventDefault();
       var myEvent = jQuery.Event('keypress');
       myEvent.target = event.target;
       myEvent.shiftKey = true;
       myEvent.keyCode = event.keyCode;
       $(document).trigger(myEvent);
    }
  });
});

I'm not sure why this doesn't work - what am I missing here?

9 Answers 9

27

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;
}
3
  • Wouldn't this capitalize the whole string though?
    – Shaded
    Commented Nov 8, 2013 at 20:19
  • 3
    This capitalizes the first letter of every word.
    – JSP64
    Commented Nov 8, 2013 at 20:23
  • 10
    This doesn't actually capitalize the input. It only makes it look like it's capitalized. Submit the form and the value sent to the server is the original value not necessarily a capitalized value. This does not answer the users questions. Why does it have so many votes? Commented Aug 25, 2015 at 19:07
15

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);
        }
    });
});
10
  • This erases the whole string when the user just wants to change the first character :/
    – JSP64
    Commented Nov 8, 2013 at 20:27
  • Ha... so you didn't just want a link back to your own fiddle? Fixed now
    – Shaded
    Commented Nov 8, 2013 at 20:27
  • I'm not seeing the whole string replaced in my fiddle.
    – Shaded
    Commented Nov 8, 2013 at 20:28
  • Try typing something, then moving the cursor back to the first character and typing again, or highlighting the first couple letters and typing something - it will clear the rest of the string. Which makes sense, since the entire value is reset.
    – JSP64
    Commented Nov 8, 2013 at 20:32
  • Ahh I see what you're saying. I thinks I can fix that
    – Shaded
    Commented Nov 8, 2013 at 20:38
4

This works for me.

$('input').keyup(function() {
  $(this).val($(this).val().substr(0, 1).toUpperCase() + $(this).val().substr(1).toLowerCase());
});
0
2

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.

1
//First letter only(absolutely). eg. Tom tom, tom
//Note: "change paste" in this function ensures this will work even if the user pasted into the input or used the autocomplete.

$('#your-input').on('change paste keydown', function(e) {
    $th_inp = $(this).val();
    inp_val = $th_inp.charAt(0).toUpperCase()+$th_inp.slice(1);
    $(this).val(inp_val);
});

//First letter (including after punctuation). eg. Tom Tom, Tom

$('#your-input').on('change keydown paste', function(e) {
  if (this.value.length = 1) {}
    var $this_val = $(this).val();
    this_val = $this_val.toLowerCase().replace(/\b[a-z]/g, function(char) {
        return char.toUpperCase();
    });
    $(this).val(this_val);
});
1
  • I tested 5-10 different functions found here on SO but this was the only one that could handle paste. Thanks!
    – Fredrik
    Commented Oct 27, 2021 at 5:45
0

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

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>
-1

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.

1
  • Does not do it real time.
    – mplungjan
    Commented Nov 8, 2013 at 20:21
-1
$('selector').blur(function(){
        $(this).val($(this).val().charAt(0).toUpperCase()+$(this).val().slice(1)); 
  });
2
  • 2
    Please read stackoverflow.com/help/how-to-answer - it's always nice to provide some explanation with the code.
    – Eel Lee
    Commented Mar 17, 2015 at 17:18
  • This doesn't really answers the question: user specifically asks to avoid the character correction onkeydown, this only works onblur. Commented Mar 17, 2015 at 17:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.