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() {
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);
}
});
});
};
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>
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.
$('selector').blur(function(){
$(this).val($(this).val().charAt(0).toUpperCase()+$(this).val().slice(1));
});
This works for me.
$('input').keyup(function() {
$(this).val($(this).val().substr(0, 1).toUpperCase() + $(this).val().substr(1).toLowerCase());
});
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.