问题描述
我有一个简单的输入数字,例如:
< input type =number/>
当输入数字或字母e以外的任何东西时,它都不起作用,但是当我输入字母e时它有效。
我检查了w3.org的规格,并且清楚地说明浮点数可以使用正常表示法例如:10.2)或科学记数法(例如:1e2)。
所以我的问题是:有没有办法阻止用户输入字母和点。换言之:有没有办法让输入数字接受 ONLY INTEGER NUMBERS ?
我有这样做的想法, Angular指令,我将作为属性输入到我的输入号码中,但我真的不知道如何完成这项工作。
编辑 :我想要做的是模拟我们现在在尝试键入除e或。以外的字母表中的任何其他字母时所具有的行为。我想说的是,我不想看到输入中出现的字母(就像现在这样)。
你应该用指令完成它是正确的。只需创建一个指令并将其附加到输入
。该指令应该监听 keypress
和/或 keydown
事件。可能也会粘贴事件。如果输入的字符是'e'或者点号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。 )}}}}}}
<脚本src =https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js>< / script>< div ng-app =app> < input type =numberyr-integer />< / div>
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”和点在输入数字中输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!