自动制作首字母大写字母

时间:2013-08-20 12:26:28

标签: javascript

我想把文本框中的第一个字母作为资本,但我不知道如何应用它。例如sitholimela ----> Sitholimela

我想将其应用于文本框。

感谢您的帮助。

4 个答案:

答案 0 :(得分:10)

请试试这个。它有效。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title>Capitalizing first letter in a textbox</title>
  <script type="text/javascript">
  function capitalize(textboxid, str) {
      // string with alteast one character
      if (str && str.length >= 1)
      {       
          var firstChar = str.charAt(0);
          var remainingStr = str.slice(1);
          str = firstChar.toUpperCase() + remainingStr;
      }
      document.getElementById(textboxid).value = str;
  }
  </script>
 <body>
  <form name="myform" method="post">
      <input type="text" id="mytextbox" onkeyup="javascript:capitalize(this.id, this.value);">
  </form>
 </body>
</html>

答案 1 :(得分:9)

CSS

input[type=text] {
    text-transform: capitalize;
}

这将使文本以这种方式显示

DEMO: http://jsfiddle.net/gvee/csC8K/

答案 2 :(得分:6)

要在 JavaScript 中执行此操作,请获取节点,并将其替换为您的转换

var textbox = document.getElementById('myTextboxId');

textbox.value = textbox.value.charAt(0).toUpperCase() + textbox.value.slice(1);

MDN页面

答案 3 :(得分:3)

工作演示......

http://jsfiddle.net/billymoon/mzXLc/1/

HTML

<input type="text" id="targetBox">

的Javascript

var capitalize = function(e){
    // if the first letter is lowercase a-z
    // ** don't run the replace unless required, to permit selecting of text **
    if(this.value.match(/^[a-z]/)){
        // replace the first letter
        this.value = this.value.replace(/^./,function(letter){
            // with the uppercase version
            return letter.toUpperCase();
        });
    }
}

// listen to key up in case of typeing, or pasting via keyboard
// listen to mouseup in case of pasting via mouse
// prefer `up` events as the action is complete at that point
document.getElementById('targetBox').addEventListener('keyup', capitalize);
document.getElementById('targetBox').addEventListener('mouseup', capitalize);