Javascript 如何在输入类型 Number 中阻止 +,-,e?

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

How to block +,-,e in input type Number?

javascripthtmlangularjs

提问by Surya Teja

When I'm giving input type number the letter eand special charecters are also displaying in input field. I want to display only digits. How to block them?

当我提供输入类型编号时,字母e和特殊字符也会显示在输入字段中。我只想显示数字。如何阻止他们?

<input type="number">

采纳答案by Sidharth Gusain

Try preventing the default behaviour if you don't like the incoming key value:

如果您不喜欢传入的键值,请尝试阻止默认行为:

document.querySelector(".your_class").addEventListener("keypress", function (evt) {
    if (evt.which != 8 && evt.which != 0 && evt.which < 48 || evt.which > 57)
    {
        evt.preventDefault();
    }
});

// 0 for null values
// 8 for backspace 
// 48-57 for 0-9 numbers
<input type="number" class="your_class">

回答by akinuri

You can block entering those chars with keydownevent

您可以使用keydown事件阻止输入这些字符

var inputBox = document.getElementById("inputBox");

var invalidChars = [
  "-",
  "+",
  "e",
];

inputBox.addEventListener("keydown", function(e) {
  if (invalidChars.includes(e.key)) {
    e.preventDefault();
  }
});
<input type="number" id="inputBox" />

but the user can still enter them if s/he does a copy/paste (or through the console). To prevent copy/paste, you can do a replace on the entered value [*].

但是如果他/她进行复制/粘贴(或通过控制台),用户仍然可以输入它们。为了防止复制/粘贴,您可以对输入的值[*]进行替换。

var inputBox = document.getElementById("inputBox");

var invalidChars = [
  "-",
  "+",
  "e",
];

inputBox.addEventListener("input", function() {
  this.value = this.value.replace(/[e\+\-]/gi, "");
});

inputBox.addEventListener("keydown", function(e) {
  if (invalidChars.includes(e.key)) {
    e.preventDefault();
  }
});
<input type="number" id="inputBox" />



* You can't really get the entered value on an input field with type set to number. You can get the entered value as long as it is a number, that is, the value passes the internal number check. If the user copy/paste 1e, suggested solution will fail.

* 您无法真正在类型设置为数字的输入字段上获取输入值。输入的值只要是数字就可以获取,即该值通过内部数字校验。如果用户复制/粘贴1e,建议的解决方案将失败。

What happens when you enter 1eis that, input field checks if it's a number, and if it's not (1eis not) it throws a warning:

当你输入时会发生什么1e,输入字段检查它是否是一个数字,如果不是(1e不是)它会抛出一个警告:

The specified value "1e" is not a valid number. The value must match to the following regular expression: -?(\d+|\d+.\d+|.\d+)([eE][-+]?\d+)?

指定的值“1e”不是有效数字。该值必须与以下正则表达式匹配:-?(\d+|\d+.\d+|.\d+)([eE][-+]?\d+)?

and the valueproperty is set to "".

并且该value属性设置为""

If you check the field's properties, you'll find valueAsNumberproperty. If the entered value is a number, input field parses the value and stores it in valueAsNumber. Since 1eis not a number, it evaluates to NaN, and NaNis assigned to valueAsNumberand valueis set to "". Though you still see 1eon the input field.

如果您检查该字段的属性,您将找到valueAsNumber属性。如果输入的值为数字,则输入字段会解析该值并将其存储在valueAsNumber. 由于1e不是数字,因此计算结果为NaN,并NaN分配给valueAsNumbervalue设置为""。虽然您仍然1e在输入字段上看到。

I've asked a question related to this problem, but no solution yet.

我已经问了一个与此问题相关的问题,但还没有解决方案。

Get the entered value on number input field, not the parsed

在数字输入字段上获取输入的值,而不是解析的值

回答by Rajesh

Instead on trying to block values, you can try to replace values that are non numeric.

您可以尝试替换非数字值,而不是尝试阻止值。

If you choose to handle keycodes, you will have to handle numKeys, numPad, shift +, crtl +etc and trying to refresh while focus is inside textbox will also fail. Prevent Default will stop lot more than incorrect values.

如果您选择处理的键码,你将不得不把手numKeysnumPadshift +crtl +等,试图刷新,而重点是内部的文本框也将失败。防止默认值将停止比不正确的值更多。

$("#input").on("input", function() {
  var nonNumReg = /[^0-9]/g
  $(this).val($(this).val().replace(nonNumReg, ''));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="tel" id="input" />
<div class="alert"></div>

回答by Callistus Asirvatham

Following form from the answers above, most of the examples above cover it, i just noticed that when inputting "E" this is still allowable so i think its best to add this into the array. I am using Jquery 3.3.1in this example.

遵循上述答案的形式,上面的大多数示例都涵盖了它,我只是注意到在输入“E”时这仍然是允许的,因此我认为最好将其添加到数组中。我在这个例子中使用了Jquery 3.3.1

Also that way whatever you enter into the array will be prevented from being keyed in into the input box

同样,您输入数组的任何内容都将被阻止输入到输入框中

Note- take the 'elementid' as the id of the element you want to apply this to similarly if you want to apply this to all inputs that are type number in JQuery --> $("input[type='number']")

注意- 如果要将其应用于 JQuery 中所有类型为数字的输入,请将 'elementid' 作为要应用它的元素的 id --> $("input[type='number']" )

var invalidChars = ["-", "e", "+", "E"];

$("input[type='number']").on("keydown", function(e){ 
    if(invalidChars.includes(e.key)){
         e.preventDefault();
    }
}):

This sample above should work on all inputs with a type of number and prevent the characters "-", "e", "+" and "E" from being keyed into the input.

上面的这个示例应该适用于所有类型为数字的输入,并防止字符“-”、“e”、“+”和“E”被键入到输入中。

UPDATE

更新

Just also notices that you are able to enter '.' as they represent decimal points which is valid for numbers. I was using this validating a telephone number and obviously (for UK) there is no '.' so that may also be another character to add to your array.

只是还注意到您可以输入“。” 因为它们代表对数字有效的小数点。我正在使用这个验证电话号码,显然(对于英国)没有“。” 所以这也可能是要添加到数组中的另一个字符。

回答by Hitesh Misro

You can do it easily using jQuery

您可以使用 jQuery 轻松完成

Try this code

试试这个代码

$(function() {
    $("#input").keypress(function(event) {
        if (event.which != 8 && event.which != 0 && (event.which < 48 || event.which > 57)) {
            $(".alert").html("Enter only digits!").show().fadeOut(2000);
            return false;
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="input" />
<div class="alert"></div>

回答by gakeko betsi

A simple solution which I used in React.

我在 React 中使用的一个简单解决方案。

onKeyDown={(evt) => ["e", "E", "+", "-"].includes(evt.key) && evt.preventDefault()}

回答by Joko Wandiro

You can check it if it's a number or not.

你可以检查它是否是一个数字。

// Restrict e, -, + for html input number
$(document).on('keypress', ':input[type="number"]', function (e) {
    if (isNaN(e.key)) {
        return false;
    }
});

回答by Prins Kumar Gupta

$("#input").on("input", function() {
  var nonNumReg = /[^0-9]/g
  $(this).val($(this).val().replace(nonNumReg, ''));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="tel" id="input" />
<div class="alert"></div>

回答by dperish

Since OP's question was tagged with 'angularjs', the cleanest solution would probably be to use a directive. Several solutions for this approach have previously been explained here:

由于 OP 的问题被标记为“angularjs”,因此最干净的解决方案可能是使用指令。此方法的几种解决方案先前已在此处解释过:

angularjs: allows only numbers to be typed into a text box

angularjs:只允许在文本框中输入数字

回答by Omid Farvid

Yo can Block by using some JQuery codes

你可以使用一些 JQuery 代码来阻止

 $('input[Type="Number"]').keypress(function (e) {
    if ('0123456789'.indexOf(e.key) == -1) {
        e.preventDefault();
    }
});

This will affect on all Numeric typed Input

这将影响所有数字类型的输入