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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
JSP64
  • 1,454
  • 1
  • 16
  • 26

9 Answers9

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;
}
Borre Mosch
  • 4,404
  • 2
  • 19
  • 28
  • Wouldn't this capitalize the whole string though? – Shaded Nov 08 '13 at 20:19
  • 3
    This capitalizes the first letter of every word. – JSP64 Nov 08 '13 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? – danielson317 Aug 25 '15 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);
        }
    });
});
JSP64
  • 1,454
  • 1
  • 16
  • 26
Shaded
  • 17,276
  • 8
  • 37
  • 62
  • This erases the whole string when the user just wants to change the first character :/ – JSP64 Nov 08 '13 at 20:27
  • Ha... so you didn't just want a link back to your own fiddle? Fixed now – Shaded Nov 08 '13 at 20:27
  • I'm not seeing the whole string replaced in my fiddle. – Shaded Nov 08 '13 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 Nov 08 '13 at 20:32
  • Ahh I see what you're saying. I thinks I can fix that – Shaded Nov 08 '13 at 20:38
  • Might want to trim() it, too to prevent a space being first. – Scott Nov 08 '13 at 20:50
  • I didn't add the `trim` as @Scott suggested, but it's updated to handle other cases you mentioned. – Shaded Nov 08 '13 at 21:01
  • Accepted. This is fast, and doesn't have any issues with moving the cursor, etc. – JSP64 Nov 08 '13 at 21:16
  • Excellent Solution. Just what I was looking for. Is their a way to allow the user to override the capital? Like if the user deletes the character and types a lowercase it accepts it? – danielson317 Aug 25 '15 at 19:13
  • Here is my solution to allow the user to override the capitalize: http://jsfiddle.net/6z1abhq2/ – danielson317 Aug 25 '15 at 19:27
4

This works for me.

$('input').keyup(function() {
  $(this).val($(this).val().substr(0, 1).toUpperCase() + $(this).val().substr(1).toLowerCase());
});
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.

Henrique Barcelos
  • 7,670
  • 1
  • 41
  • 66
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);
});
Dexter
  • 74
  • 8
  • I tested 5-10 different functions found here on SO but this was the only one that could handle paste. Thanks! – Fredrik Oct 27 '21 at 05: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);
            }
        });
    });
};
Apurva
  • 148
  • 1
  • 14
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>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Nahabwe Edwin
  • 521
  • 4
  • 6
-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.

Community
  • 1
  • 1
johnsoe
  • 664
  • 1
  • 5
  • 13
-1
$('selector').blur(function(){
        $(this).val($(this).val().charAt(0).toUpperCase()+$(this).val().slice(1)); 
  });
  • 2
    Please read http://stackoverflow.com/help/how-to-answer - it's always nice to provide some explanation with the code. – Eel Lee Mar 17 '15 at 17:18
  • This doesn't really answers the question: user specifically asks to avoid the character correction onkeydown, this only works onblur. – Alvaro Montoro Mar 17 '15 at 17:52