Html <input type="number"> 允许 2 个小数位

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

Allow 2 decimal places in <input type="number">

htmlnumbers

提问by nubteens

I have a <input type="number">and I want to restrict the input of the users to purely numbers or numbers with decimals up to 2 decimal places.

我有一个<input type="number">,我想将用户的输入限制为纯数字或小数点后最多 2 个小数位的数字。

Basically, I am asking for a price input.

基本上,我要求输入价格。

I wanted to avoid doing regex. Is there a way to do it?

我想避免做正则表达式。有没有办法做到这一点?

<input type="number" required name="price" min="0" value="0" step="any">

回答by Michael Benjamin

Instead of step="any", which allows for any number of decimal places, use step=".01", which allows up to two decimal places.

代替step="any"允许任意数量的小数位的 ,使用step=".01"允许最多两位小数的 。

More details in the spec: https://www.w3.org/TR/html/sec-forms.html#the-step-attribute

规范中的更多详细信息:https: //www.w3.org/TR/html/sec-forms.html#the-step-attribute

回答by Weston Ganger

If case anyone is looking for a regex that allows only numbers with an optional 2 decimal places

如果有人正在寻找一个只允许带有可选的 2 个小数位的数字的正则表达式

^\d*(\.\d{0,2})?$

For an example, I have found solution below to be fairly reliable

例如,我发现下面的解决方案相当可靠

HTML:

HTML:

<input name="my_field" pattern="^\d*(\.\d{0,2})?$" />

JS / JQuery:

JS/JQuery:

$(document).on('keydown', 'input[pattern]', function(e){
  var input = $(this);
  var oldVal = input.val();
  var regex = new RegExp(input.attr('pattern'), 'g');

  setTimeout(function(){
    var newVal = input.val();
    if(!regex.test(newVal)){
      input.val(oldVal); 
    }
  }, 0);
});

回答by Ultimater

For currency, I'd suggest:

对于货币,我建议:

<div><label>Amount $
    <input type="number" placeholder="0.00" required name="price" min="0" value="0" step="0.01" title="Currency" pattern="^\d+(?:\.\d{1,2})?$" onblur="
this.parentNode.parentNode.style.backgroundColor=/^\d+(?:\.\d{1,2})?$/.test(this.value)?'inherit':'red'
"></label></div>

See http://jsfiddle.net/vx3axsk5/1/

http://jsfiddle.net/vx3axsk5/1/

The HTML5 properties "step", "min" and "pattern" will be validated when the form is submit, not onblur. You don't need the stepif you have a patternand you don't need a patternif you have a step. So you could revert back to step="any"with my code since the pattern will validate it anyways.

HTML5 属性“step”、“min”和“pattern”将在提交表单时进行验证,而不是 onblur。step如果您有 a 则不需要 ,如果您有pattern则不需要patterna step。所以你可以恢复到step="any"我的代码,因为模式无论如何都会验证它。

If you'd like to validate onblur, I believe giving the user a visual cue is also helpful like coloring the background red. If the user's browser doesn't support type="number"it will fallback to type="text". If the user's browser doesn't support the HTML5 pattern validation, my JavaScript snippet doesn't prevent the form from submitting, but it gives a visual cue. So for people with poor HTML5 support, and people trying to hack into the database with JavaScript disabled or forging HTTP Requests, you need to validate on the server again anyways. The point with validation on the front-end is for a better user experience. So as long as most of your users have a good experience, it's fine to rely on HTML5 features provided the code will still works and you can validate on the back-end.

如果您想验证 onblur,我相信为用户提供视觉提示也很有帮助,例如将背景着色为红色。如果用户的浏览器不支持type="number",它将回退到type="text". 如果用户的浏览器不支持 HTML5 模式验证,我的 JavaScript 代码段不会阻止表单提交,但会提供视觉提示。因此,对于 HTML5 支持不佳的人,以及试图在禁用 JavaScript 或伪造 HTTP 请求的情况下入侵数据库的人,您无论如何都需要再次在服务器上进行验证。前端验证的重点是为了更好的用户体验。因此,只要您的大多数用户都有良好的体验,只要代码仍然有效并且您可以在后端进行验证,就可以依赖 HTML5 功能。

回答by Sachin Sudhakar Sonawane

Step 1:Hook your HTML number input box to an onchange event

第 1 步:将您的 HTML 数字输入框与 onchange 事件挂钩

myHTMLNumberInput.onchange = setTwoNumberDecimal;

or in the HTML code

或在 HTML 代码中

<input type="number" onchange="setTwoNumberDecimal" min="0" max="10" step="0.25" value="0.00" />

Step 2: Write the setTwoDecimalPlacemethod

第 2 步:编写setTwoDecimalPlace方法

function setTwoNumberDecimal(event) {
    this.value = parseFloat(this.value).toFixed(2);
}

You can alter the number of decimal places by varying the value passed into the toFixed()method. See MDN docs.

您可以通过改变传递给toFixed()方法的值来改变小数位数。请参阅MDN 文档

toFixed(2); // 2 decimal places
toFixed(4); // 4 decimal places
toFixed(0); // integer

回答by Nilesh Gajare

Try this for allowing only 2 decimal in input type

试试这个,在输入类型中只允许 2 位小数

<input type="number" step="0.01" class="form-control"  />

Or Use jQuery as suggested by @SamohtVII

或者按照@SamohtVII 的建议使用 jQuery

$( "#ELEMENTID" ).blur(function() {
    this.value = parseFloat(this.value).toFixed(2);
});

回答by SamohtVII

I found using jQuery was my best solution.

我发现使用 jQuery 是我最好的解决方案。

$( "#my_number_field" ).blur(function() {
    this.value = parseFloat(this.value).toFixed(2);
});

回答by Obaidul Haque

Use this code

使用此代码

<input type="number" step="0.01" name="amount" placeholder="0.00">

By default Step value for HTML5 Input elements is step="1".

默认情况下,HTML5 Input 元素的 Step 值为 step="1"。

回答by ILLUSTRAY KING

just write

写就好了

<input type="number" step="0.1" lang="nb">

lang='nb" let you write your decimal numbers with comma or period

lang='nb" 让你用逗号或句点写十进制数

回答by xemasiv

On input:

输入时:

step="any"
class="two-decimals"

On script:

在脚本上:

$(".two-decimals").change(function(){
  this.value = parseFloat(this.value).toFixed(2);
});