10

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

我想将此应用于文本框。

谢谢你的帮助。

4

4 回答 4

11

请试试这个。有用。

<!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>
于 2013-08-20T12:46:30.773 回答
9

CSS

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

这将使文本以这种方式出现

演示:http: //jsfiddle.net/gvee/csC8K/

于 2013-08-20T12:28:24.533 回答
7

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

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

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

MDN 页面

于 2013-08-20T12:27:36.920 回答
4

工作演示...

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);
于 2013-08-20T12:37:34.503 回答