Html HTML5 输入标签中的格式编号

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

Format number in an HTML5 input tag

html

提问by Marcus H?glund

This is my input

这是我的输入

<input type="number" id="inputNumbers" step="0.01" ></input>

Is it possible to only allow users to enter numbers that match the pattern '0.00', like the way I declare it in the step attribute, without using JavaScript?

是否可以只允许用户输入与模式“0.00”匹配的数字,就像我在 step 属性中声明它的方式一样,而不使用 JavaScript?

Example: If the user types '1.23' and then tries to enter a new number, decimal or comma it can't and the number stays at '1.23'.

示例:如果用户键入“1.23”,然后尝试输入新数字、小数点或逗号,则无法输入,并且数字保持为“1.23”。

If there's not a way to match the step attribute, Is it possible to only allow one decimal in the number?

如果没有匹配 step 属性的方法,是否可以只允许数字中的一位小数?

回答by nouseforname

I think you can try something like this:

我想你可以尝试这样的事情:

input type="number" name="number" pattern="([0-9]{1,3}).([0-9]{1,3})" title="Must contain a decimal number">

see here

这里

Added Plunkr: Plunker

添加了 Plunkr: Plunker

回答by UniCoder

It can be achieved using javascript with corner case handling using toLocaleString()

它可以使用 javascript 与使用 toLocaleString() 的边角案例处理来实现

function getChange(){
  // 48 - 57 (0-9)
  var str1 = valueRef.value;
  if((str1[str1.length-1]).charCodeAt() < 48 || (str1[str1.length-1]).charCodeAt() > 57){
    valueRef.value = str1.substring(0,str1.length-1 );
    return;
  } 

 // t.replace(/,/g,'')
  let str = (valueRef.value).replace(/,/g,'');

  let value = +str;

  valueRef.value = value.toLocaleString();
}

Working Codepen Demo Link

工作 Codepen 演示链接

回答by Ctc

function inputLimiter(e,allow) {
    var AllowableCharacters = '';

    if (allow == 'custom'){AllowableCharacters=' 1234567890.';}


    var k = document.all?parseInt(e.keyCode): parseInt(e.which);
    if (k!=13 && k!=8 && k!=0){
        if ((e.ctrlKey==false) && (e.altKey==false)) {
        return (AllowableCharacters.indexOf(String.fromCharCode(k))!=-1);
        } else {
        return true;
        }
    } else {
        return true;
    }
    
    }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="NameCharacters" onkeypress="return inputLimiter(event,'custom')" value="" maxlength="4" /></p>

In Javascript. But this was as far as I got, will just leave this here for awhile, need to handle other stuffs.

在 JavaScript 中。但这是我得到的,将在这里放一段时间,需要处理其他事情。