1

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.

Cody Coderson
  • 411
  • 1
  • 9
  • 21
  • what is the purpose of using `setSelectionRange` and `selectionStart`? – gurvinder372 Jan 06 '18 at 09:48
  • 3
    Possible duplicate of [Capitalize First Letter of each word in a String - JavaScript](https://stackoverflow.com/questions/32589197/capitalize-first-letter-of-each-word-in-a-string-javascript) – Durga Jan 06 '18 at 09:52

2 Answers2

7

You 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.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input>
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
1

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";
Chaitanya Desai
  • 333
  • 3
  • 17
  • Depends if you want to use the inputted value transformed or not, as this will simply transform the display to the user rather than the underlying data – Craig Myles Aug 23 '18 at 02:59