Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
520 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...