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
Format number in an HTML5 input tag
提问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
回答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();
}
回答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 中。但这是我得到的,将在这里放一段时间,需要处理其他事情。