user3861895
user3861895

Reputation: 3

Javascript Capitalize the First Name in a Form

I am trying to make the following work onChange when a user leaves the first name field. I cannot see what I am doing wrong.

function changeCase()  //Change first letter to uppercase and the rest to lowercase
{
  var fName = document.getElementById('firstName');
  var properCaseString = fName.substring(0,1).toUpperCase() + fName.substring(1,fName.length);
  document.getElementById('firstName').value = properCaseString;
}

Upvotes: 0

Views: 163

Answers (2)

technosaurus
technosaurus

Reputation: 7812

You can (sort of) do this with CSS.

//won't change a name that is all caps
<style>
#firstName{
  text-transform:capitalize;
}
</style>

or if there is only 1 word, so if they entered "mary jane" it would be "Mary jane"

<style>
#firstName{ text-transform: lowercase; }
#firstName:first-letter { text-transform: uppercase; }
</style>

Upvotes: 1

Lochemage
Lochemage

Reputation: 3974

fName is an element, not a string:

var fName = document.getElementById('firstName').value;

is probably what you actually wanted to get.

Upvotes: 2

Related Questions