I have a javascript code that auto-capitalizes first letter of every sentence as typed in any input field(s) of the page.
The code is as follows:
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(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);
}
});
});
});//]]>
</script>
I need help in transforming the above code to autocapitalize first letter of every word typed in input fields instead of just the first word only.
I have a javascript code that auto-capitalizes first letter of every sentence as typed in any input field(s) of the page.
The code is as follows:
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(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);
}
});
});
});//]]>
</script>
I need help in transforming the above code to autocapitalize first letter of every word typed in input fields instead of just the first word only.
Share Improve this question asked Jan 6, 2018 at 9:44 Cody CodersonCody Coderson 4211 gold badge10 silver badges22 bronze badges 2-
what is the purpose of using
setSelectionRange
andselectionStart
? – gurvinder372 Commented Jan 6, 2018 at 9:48 - 3 Possible duplicate of Capitalize First Letter of each word in a String - JavaScript – Durga Commented Jan 6, 2018 at 9:52
2 Answers
Reset to default 8You can simply apply this method at the keyup
event
function toTitleCase( str )
{
return str.split(/\s+/).map( s => s.charAt( 0 ).toUpperCase() + s.substring(1).toLowerCase() ).join( " " );
}
And now use it as
$('input').on('keyup', function(event) {
var $t = $(this);
$t.val( toTitleCase( $t.val() ) );
});
Demo
function toTitleCase(str) {
return str.split(/\s+/).map(s => s.charAt(0).toUpperCase() + s.substring(1).toLowerCase()).join(" ");
}
$('input').on('keyup', function(event) {
var $t = $(this);
$t.val(toTitleCase($t.val()));
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input>
Don't make it hard. If you can do like this.
Apply this CSS in to the field.
.capitalize {
text-transform: capitalize;
}
for jquery:
$('#id').addClass('capitalize');
for javascript:
document.getElementById("id").className="capitalize";