A simple way to achieve this is:
nameOfPerson.charAt(0).toUpperCase() + nameOfPerson.substring(1);
When to do it?
Blur
You can do it when input looses focus(blur
) event. This will allow user to input in any format and when he is done, then you apply your formatting.
function formatting() {
var nameOfPerson = this.value
this.value = nameOfPerson.charAt(0).toUpperCase() + nameOfPerson.substring(1).toLowerCase();
}
var input = document.getElementById("nameOfPerson");
input.addEventListener('blur', formatting)
<input type="text" id="nameOfPerson" placeholder="type your name">
Input
Or you can enforce formatting using input
event. This will take care of typing and pasting actions.
function formatting() {
var nameOfPerson = this.value
this.value = nameOfPerson.charAt(0).toUpperCase() + nameOfPerson.substring(1).toLowerCase();
}
var input = document.getElementById("nameOfPerson");
input.addEventListener('input', formatting)
<input type="text" id="nameOfPerson" placeholder="type your name">
Pointers
- Avoid binding handlers in HTML. Anyone can change DOM using dev tools and change behaviour of your page.
textContent
as name suggest is used for text bindings and will return static text. Inputs have value binding and you should use .value
- When you use
onclange="formatting()"
, handler will not have context pointing to element and you will have to fetch it again and again and DOM queries are expensive. Using .addEventListener()
will bind context and is preferred as you can add more than 1 handler.
- In
(nameOfPerson - nameOfPerson[0])
, -
operator will convert value to numeric value and would yield NaN
. When dealing with strings, use string helper functions.