Cody Coderson
Cody Coderson

Reputation: 421

Javascript to auto-capitalize first letter of every word in input fields

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.

Upvotes: 1

Views: 4665

Answers (2)

Chaitanya Desai
Chaitanya Desai

Reputation: 323

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";

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68433

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>

Upvotes: 8

Related Questions