Capitalize first character of user input in real time with JQuery
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.
This works for me.
$('input').keyup(function() {
$(this).val($(this).val().substr(0, 1).toUpperCase() + $(this).val().substr(1).toLowerCase());
});
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;
}
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);
}
});
});