防止在输入数字中键入字母“e"和点 [英] Prevent the letter 'e' and dots from being typed in an input number
问题描述
我有一个简单的输入数字,如下所示:
当尝试输入数字或字母e"以外的任何内容时,它不起作用,但当我输入字母e"时它起作用.
我查看了 w3.org 规范,它清楚地说明可以使用普通记数法(例如:10.2)或科学记数法(例如:1e2)来输入浮点数.
所以我的问题是:有没有办法阻止用户输入 e 字母和点.换句话说:有没有办法让输入的数字接受ONLY INTEGER NUMBERS?
我想用一个 Angular 指令来做这件事,我将把它作为一个属性输入到我的输入数字中,但我真的不知道如何使它工作.
编辑:我想做的是模拟我们现在尝试在字母表中键入除e"以外的任何其他字母时相同的行为, 或者 ".".我想说的是,我不想看到输入中出现的字母(就像现在这样).
您是正确的,应该使用指令来完成.只需创建一个指令并将其附加到 input
.这个指令应该监听 keypress
和/或 keydown
事件.也可能粘贴事件.如果输入的字符是e"或点——调用 event.preventDefault();
angular.module('app', []).directive('yrInteger', yrInteger);函数 yrInteger() {返回 {限制:'A',链接:函数(范围,元素,属性){element.on('keypress', function(event) {如果 ( !isIntegerChar() )event.preventDefault();函数 isIntegerChar() {返回/[0-9]|-/.test(String.fromCharCode(event.which))}})}}}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><div ng-app="app"><输入类型=数字"整数/>
I have a simple input number like this:
<input type="number"/>
When trying to input anything other than a number or the letter "e", it doesn't work, but when I type the letter "e" it works.
I checked w3.org specs, and it states clearly that floating numbers can be typed using the normal notation (ex : 10.2) or the scientific notation (ex : 1e2).
So my question is : Is there a way to prevent the user from typing e letters and dots. Said in another way : Is there a way to make the input number accept ONLY INTEGER NUMBERS ?
I have the idea of doing that with an Angular directive that I will input as an attribute to my input number, but I really don't know how to make that work.
EDIT : What I would like to do is to simulate the same behaviour that we have now when trying to type any other letter in the alphabet other than "e", or ".". What I want to say is that I do not want to see the letter appearing in the input (Like it is the case now).
You are correct that it should be done with a directive. Simply create a directive and attach it to the input
. This directive should listen for keypress
and/or keydown
events. Possibly paste events as well. If the char entered is an 'e' or dot -- call event.preventDefault();
angular.module('app', [])
.directive('yrInteger', yrInteger);
function yrInteger() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.on('keypress', function(event) {
if ( !isIntegerChar() )
event.preventDefault();
function isIntegerChar() {
return /[0-9]|-/.test(
String.fromCharCode(event.which))
}
})
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<input
type="number"
yr-integer
/>
</div>
这篇关于防止在输入数字中键入字母“e"和点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!