Javascript Typescript + Html:如何在输入字段中强制大写

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

Typescript + Html: How to force uppercase in an input field

javascripthtmlangulartypescript

提问by Nobady

I'm working with angular (typescript) and I have a modelform in html where the user has to insert a code field and a description field.

我正在使用 angular(打字稿),并且我在 html 中有一个模型表单,用户必须在其中插入代码字段和描述字段。

The code field must always be entered by the user, always in uppercase.

代码字段必须始终由用户输入,始终为大写。

I found and followed this question: How to convert input value to uppercase in angular 2 (value passing to ngControl)

我发现并遵循了这个问题: How to convert input value to uppercase in angular 2 (value传递给ngControl)

but the last letter that the user inserts remains lowercase however .. The fundamental thing is that the database always comes in all uppercase (I also put a limit of 4 characters that works properly) this is my code now, but as written above it does not work properly:

但是用户插入的最后一个字母仍然是小写字母.. 基本的事情是数据库总是全部大写(我也限制了 4 个可以正常工作的字符)这是我现在的代码,但正如上面写的那样不能正常工作:

<input type="text" id="code" #code class="form-control" formControlName="code" maxlength="4"
                 (input)="code.value=$event.target.value.toUpperCase()">

has anyone found a quick, functional and fast solution?

有没有人找到快速、实用且快速的解决方案?

thank you!

谢谢你!

回答by Ali Heikal

You can simply add oninput="this.value = this.value.toUpperCase()"in your <input>tag and it will instantly convert any input in your input field to Uppercase.

您可以简单地添加 oninput="this.value = this.value.toUpperCase()"在您的<input>标记,它会立即转换任何输入你的输入字段为大写。

回答by DForsyth

If you're working with ngModel, you can use ngModelChangeto do it this way with JavaScript's .ToUpperCase().

如果您正在使用ngModel,您可以使用ngModelChangeJavaScript 的.ToUpperCase()以这种方式进行操作。

<input [ngModel]="person.Name" (ngModelChange)="person.Name = $event.toUpperCase()">

回答by Sampaguita

This worked for me. I just used keyup and whenever a user adds a character it automatically converts it to Uppercase, not just in the UI but in the model as well.

这对我有用。我只是使用了 keyup,每当用户添加一个字符时,它都会自动将其转换为大写,不仅在 UI 中,而且在模型中也是如此。

(keyup)="form.patchValue({name: $event.target.value.toUpperCase()})"

回答by Fenton

You can use a patternattribute to limit the allowed input. You may also want to assist the user by upper-casing their input.

您可以使用pattern属性来限制允许的输入。您可能还希望通过大写他们的输入来帮助用户。

<input type="text" pattern="[A-Z]*" name="example" />