javascript 自动将大写字母转换为第一个字母

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18335029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:31:47  来源:igfitidea点击:

Making Caps to the first letter automatically

javascript

提问by IT Forward

I want to make the first letter in a text box to be capital but i have no idea on how i can apply it. e.g sitholimela ----> Sitholimela

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

I want to apply this to a text box.

我想将此应用于文本框。

Thanks for your help.

谢谢你的帮助。

回答by Naresh Kumar Nakka

Please try this. It works.

请试试这个。有用。

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

回答by gvee

CSS

CSS

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

This will make the text appearin this way.

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

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

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

回答by Paul S.

To do this in JavaScript, get the node, and replace it's valuewith your transformation

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

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

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

MDN pages

MDN 页面

回答by Billy Moon

Working demo...

工作演示...

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

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

HTML

HTML

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

Javascript

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);