I am trying to automatically smooth out the first character of a text field / input that the user enters. 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 is that it shows a 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 convert the event in flight (or intercept it, prevent by default and fire a modified new event).
Here is what I have now that does not 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 is not working - what am I missing here?
javascript jquery string javascript-events
Jsp64
source share