自动大写输入字段中每个单词的第一个字母

时间:2016-12-08 20:33:32

标签: javascript

我有多个获取城市的输入字段。我希望在用户输入城市名称时将每个单词的第一个字母 设置为自动大写,而其余字母则强制为小写< /强>

注意:由于我的要求,CSS text-transform属性不起作用,因为它只修改单词的第一个字母 - - 如果用户键入超出第一个字母的大写字母信,不会调整它。

到目前为止,我有这个JavaScript:

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

成功将整个输入转换为小写。

2 个答案:

答案 0 :(得分:5)

有关详细信息,请参阅内联评论:

&#13;
&#13;
// 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(" "); 
}
&#13;
<input type="text" id="txtTest">
&#13;
&#13;
&#13;

答案 1 :(得分:3)

你可以使用css进行这个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"/>