Charles L.
Charles L.

Reputation: 1970

Auto Capitalize ONLY the First Letter of Each Word in an Input Field

I have multiple input fields that obtain a city. I would like while the user is imputing the city name that the first letter of each word to auto capitalize, while the rest of the letters are forced lower case.

NOTE: Because of my requirements, the CSS text-transform property won't work because it only modifies the first letter of the words - - if the user types capital letters beyond the first letter, that won't adjust it.

So far i have this JavaScript:

function forceLower(strInput) {
  strInput.value=strInput.value.toLowerCase();
}

Which is successfully converting the entire input to lowercase.

Upvotes: 2

Views: 5138

Answers (2)

Scott Marcus
Scott Marcus

Reputation: 65855

See comments inline for details:

// Get a reference to the input and wire it up to an input event handler that
// calls the fixer function
document.getElementById("txtTest").addEventListener("input", forceLower);

// Event handling functions are automatically passed a reference to the
// event that triggered them as the first argument (evt)
function forceLower(evt) {
  // Get an array of all the words (in all lower case)
  var words = evt.target.value.toLowerCase().split(/\s+/g);
  
  // Loop through the array and replace the first letter with a cap
  var newWords = words.map(function(element){   
    // As long as we're not dealing with an empty array element, return the first letter
    // of the word, converted to upper case and add the rest of the letters from this word.
    // Return the final word to a new array
    return element !== "" ?  element[0].toUpperCase() + element.substr(1, element.length) : "";
  });
  
 // Replace the original value with the updated array of capitalized words.
 evt.target.value = newWords.join(" "); 
}
<input type="text" id="txtTest">

Upvotes: 6

Ishey4
Ishey4

Reputation: 327

you can use css for this text-transform: capitalize

function firstCap(str){
  var returnVar='';
  var strSplit=str.split(' ');
 for(var i=0;i<strSplit.length;i++){
 returnVar=returnVar+strSplit[i].substring(0,1).toUpperCase()+strSplit[i].substring(1).toLowerCase() +' ';
  }
return returnVar
}
div , input {text-transform: capitalize;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div> this is only the first lettter</div>
<input type="text"/>

Upvotes: 4

Related Questions