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
Solution 1:
See comments inline for details:
// Get a reference to the input and wire it up to an input event handler that// calls the fixer functiondocument.getElementById("txtTest").addEventListener("input", forceLower);
// Event handling functions are automatically passed a reference to the// event that triggered them as the first argument (evt)functionforceLower(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 capvar 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 arrayreturn 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(" ");
}
<inputtype="text"id="txtTest">
Solution 2:
you can use css for this text-transform: capitalize
functionfirstCap(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;}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div> this is only the first lettter</div><inputtype="text"/>
Post a Comment for "Auto Capitalize Only The First Letter Of Each Word In An Input Field"