Javascript 如何使文本字段中的所有内容都为大写/大写?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3858488/
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-08-23 06:22:59  来源:igfitidea点击:

How to make everything in a textfield be capital letters / uppercase?

javascriptjqueryhtmlcapitalization

提问by randomizertech

I want to make everything I write in a textfield to be capital letters. As I write, not after losing focus.

我想让我在文本字段中写的所有内容都是大写字母。在我写的时候,不是在失去焦点之后。

How do I do this using jQuery?

我如何使用 jQuery 做到这一点?

回答by Brandon

I would use CSS for this.

我会为此使用 CSS。

Just add text-transform: uppercaseto your styling, and then on the server side you can convert it to uppercase.

只需添加text-transform: uppercase到您的样式中,然后在服务器端您就可以将其转换为大写。

input {
  text-transform: uppercase;
}

回答by Gazler

$('input[type=text]').keyup(function() {
    $(this).val($(this).val().toUpperCase());
});

回答by Cpt Balu

Use
oninput='this.value=this.value.toUpperCase();
This event is just for such cases, is fired after user input (pressing key) but before updating (displaying value), so with this typed text won't flicker while converting, and value is also correct (not like using only style to alter display without changing real data).

使用
oninput='this.value=this.value.toUpperCase();
此事件仅适用于此类情况,在用户输入(按键)之后但在更新(显示值)之前触发,因此输入的文本在转换时不会闪烁,并且值也是正确的(不像只使用样式来在不改变真实数据的情况下改变显示)。

回答by sambomartin

You may need to use combination of these.

您可能需要使用这些的组合。

using the text-transform style only renders the type in upper-case, although the value may well be lower case.

使用 text-transform 样式仅以大写形式呈现类型,尽管该值很可能是小写形式。

The javascript will only change current text to upper once the field changes or focus is lost

一旦字段更改或焦点丢失,javascript 只会将当前文本更改为上

you can use gazler's jquery or simply inline javascript

您可以使用 gazler 的 jquery 或简单地内联 javascript

e.g. onblur='javascript:this.value=this.value.toUpperCase();'

例如 onblur='javascript:this.value=this.value.toUpperCase();'

This means that the text value will appear uppercase and actually be uppercased when the value changes / control loses focus.

这意味着文本值将显示为大写,并且在值更改/控件失去焦点时实际为大写。

HTH Sam

山姆

回答by sean2078

To build on @Gazler's answer, an enhanced solution that better handles modifier keys ( assuming that you have a placeholder of mixed case and cannot set text-transform: uppercase;):

以@Gazler 的回答为基础,一个增强的解决方案可以更好地处理修饰键(假设您有一个大小写混合的占位符并且无法设置text-transform: uppercase;):

$('.search-input input[type=text]').keyup(function() {
    var v = $(this).val();
    var u = v.toUpperCase();
    if( v != u ) $(this).val( u );
})