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?