文本框只允许输入数字
Applications expecting numeric values for the input is generally a pain for developers. Because we have to check given values whether they are number or alphabet. We have some text input element for html. We want to get the number of the person. How can we achieve that easily?
期望输入值为数字的应用程序通常会使开发人员感到痛苦。 因为我们必须检查给定的值是数字还是字母。 我们有一些用于html的文本输入元素。 我们想得到那个人的号码。 我们如何轻松实现这一目标?
纯JavaScript (Pure JavaScript)
By using JavaScript events is the most reliable method. We will write some JavaScript for onkeypress event and check the key code. This is a simple code where we check the entered values ASCII codes and if they are inside the number range we return them.
通过使用JavaScript事件是最可靠的方法。 我们将为onkeypress事件编写一些JavaScript,并检查键代码。 这是一个简单的代码,其中我们检查输入的值ASCII代码,如果它们在数字范围内,则将其返回。
<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'></input>
onkeypress is the event will be triggered
onkeypress是事件将被触发
return will return code if the code is number which is between 48 and 57
如果代码是介于48和57之间的数字,则return将返回代码
HTML5(HTML5)
Html5 provides native tag which can only accept numeric input. We can use input
tag with the number
type which will accept only decimal numbers.
HTML5提供只能接受数字输入的本机标记。 我们可以使用带有number
类型的input
标签,该类型仅接受十进制数字。
<input type="number">
At least keep in mind that to make things more secure server side filtering is a must. Do not values provided by the client side.
至少要记住,使事情更安全的服务器端过滤是必须的。 不要提供客户端提供的值。
翻译自: https://www.poftut.com/html-text-input-allow-numeric-input/
文本框只允许输入数字