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?
//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);
});
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);
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With