如何在 Javascript 中输入时自动将所有内容变为小写
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6999649/
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
How to make everything lowercase automatically in Javascript as they type it in
提问by Jordash
How do I make all of the characters of a text box lowercase as the user types them into a text field in Javascript?
当用户将文本框的所有字符输入到 Javascript 中的文本字段时,如何将它们变成小写?
<input type="text" name="thishastobelowercase">
Thanks for any help.
谢谢你的帮助。
回答by Justin Beckwith
I would just make CSS do this for you instead of monkeying around with javascript:
我只会让 CSS 为你做这件事,而不是用 javascript 胡闹:
<input type="text" name="tobelowercase" style="text-transform: lowercase;">
回答by Mrchief
Two ways:
两种方式:
Using CSS:
使用CSS:
.lower {
text-transform: lowercase;
}
<input type="text" name="thishastobelowercase" class="lower">
Using JS:
使用JS:
<input type="text" name="thishastobelowercase" onkeypress="this.value = this.value.toLowerCase();">
回答by bjornd
$('input').keyup(function(){
this.value = this.value.toLowerCase();
});
回答by BishopRook
Does it only have to displayin lowercase, or does it have to belowercase? If you want to displaylowercase, you can use CSS text-transform: lowercase
.
它只需要以小写显示,还是必须是小写?如果要显示小写,可以使用 CSS text-transform: lowercase
。
You need to enforce this constraint server-side anyway, because the user can disable any JS code you put in to enforce that it remains lowercase.
无论如何,您都需要在服务器端强制执行此约束,因为用户可以禁用您输入的任何 JS 代码以强制它保持小写。
My suggestion: use the CSS text-transform
to make it always display in lowercase, and then do a toLower
or your language's variant of it on the server-side before you use it.
我的建议:使用 CSStext-transform
使其始终以小写形式显示,然后toLower
在使用之前在服务器端对其进行 a或您的语言的变体。
回答by Doglas
This is a mask for the type of validation that you want
这是您想要的验证类型的掩码
(function($) {
$.fn.maskSimpleName = function() {
$(this).css('text-transform', 'lowercase').bind('blur change', function(){
this.value = this.value.toLowerCase();
});
}
})(jQuery);
The advantage of using it is that the cursor will not go to the end of the input each character entered, as it would if using the a keyup or keupress solution.
使用它的好处是光标不会像使用 a keyup 或 keupress 解决方案那样移动到输入的每个字符的末尾。
$('#myinput').maskSimpleName();
This is a way to use it.
这是一种使用方法。
Obs: This mask sends the data in lowercase to the server as well.
Obs:这个掩码也将小写的数据发送到服务器。
回答by Kardo
Bootstrap Text transform:
Bootstrap 文本转换:
<p class="text-lowercase">Lowercased text.</p>
<p class="text-uppercase">Uppercased text.</p>
<p class="text-capitalize">CapiTaliZed text.</p>