自动将大写字母设置为第一个字母
Making Caps to the first letter automatically
我想将文本框中的第一个字母设为大写,但我不知道如何应用它。例如sitholimela---->Sitholmela
我想将此应用于文本框。
谢谢你的帮助。
请尝试一下。它有效。
<!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>
CSS
input[type=text] {
text-transform: capitalize;
}
这将使文本以这种方式出现。
演示:http://jsfiddle.net/gvee/csC8K/
要在JavaScript中执行此操作,请获取节点,并用转换替换其值
var textbox = document.getElementById('myTextboxId');
textbox.value = textbox.value.charAt(0).toUpperCase() + textbox.value.slice(1);
MDN页面
document.getElementById
String.prototype.charAt
String.prototype.toUpperCase
String.prototype.slice
正在进行演示
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);
相关文章:
- 使用数据上的角度更改设置集合的第一个元素的动画
- 如何设置第一个手风琴面板关闭
- 将焦点设置在下拉切换的角度 js 上的第一个输入字段上
- 用Javascript将焦点设置在select元素上会将第一个项目滚动到视图之外
- 设置第一个单选按钮是在车把模板中检查的
- 如何根据 URL 中符号后的第一个字符串设置变量
- JavaScript:将变量设置为第一个可用值
- 如何在文本框点击事件中设置文本框中字符的第一个位置---Chrome问题
- 将焦点设置在带有错误消息的第一个输入元素上,并将包含它的 TabStrip 选项卡设置为活动状态
- ng-init 未在 ng-options 中设置第一个选择选项
- 如何在引导日期设置每月的第一个日期和最后一个日期
- 为什么 CSS 选择器只设置第一个匹配 svg 路径的样式
- 如何将第一个选择选项设置为始终为空
- 如何在用户完成第一个输入文本的键入后设置和聚焦最后一个输入文本
- 根据第一个询问的输入设置输入类型范围的最小值
- 使用按钮单击将 jQuery UI 可排序元素设置为第一个位置
- 在角度 js 中将下拉列表中的第一个值设置为粗体
- 将selectedIndex设置为下面的第一个选项和选项组
- 仅在第一个图像上设置jQuery attr()
- JS Cookie设置在2个地方,不覆盖第一个设置