javascript 从输入 type=number 中删除前导零
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30626094/
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
Remove leading zeros from input type=number
提问by Alessio Dal Bianco
I noticed that if i use <input type="number" />
the leading zeros are not removed. I also saw a lot of discussion on how keepingleading zeros.
我注意到如果我使用<input type="number" />
前导零不会被删除。我还看到了很多关于如何保持前导零的讨论。
For example "000023" and "23" are the same number and i think that it doesn't make sense keeping those zeros.
例如“000023”和“23”是相同的数字,我认为保留这些零没有意义。
采纳答案by bhanu.cs
just use a regular expression like this
只需使用这样的正则表达式
textboxText= textboxText.replace(/^0+/, '')
回答by Moses Aprico
I'm going to give an example with react usage. It uses state
which store the value of the field. But, I think u can replace it with whatever variable you like.
我将举一个反应用法的例子。它使用state
which 存储字段的值。但是,我认为您可以用您喜欢的任何变量替换它。
<input type='number' value={Number(this.state.myNumber).toString()}/>
<input type='number' value={Number(this.state.myNumber).toString()}/>
In my case, myNumber
stores a year number. This way, the year 2018
(for example) won't be displayed mistakenly as 02018
.
就我而言,myNumber
存储年份编号。这样,年份2018
(例如)就不会错误地显示为02018
.
回答by bitifet
Html input tags always return text, not numbers, even its content can be coerced to numerical format, dates, etc...
Html 输入标签总是返回文本,而不是数字,甚至其内容也可以被强制为数字格式、日期等...
So next you should convert that input to actual number format:
所以接下来您应该将该输入转换为实际数字格式:
parseInt(myNum); // If you expect an integer.
parseFloat(myNum); // If you expect floating point number.
回答by Vasyl Senko
HTML5 has <input type="tel">
for this purpose
HTML5<input type="tel">
为此目的
回答by RJ Anoop
You can try this.
你可以试试这个。
str1 = str.replace(/^0+/,'');
回答by Parag Gawande
Try this :
试试这个 :
<!DOCTYPE html>
<html>
<body>
<input type="number" id="txtfield" /><button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var myNumber = document.getElementById("txtfield").value;
document.write(parseInt(myNumber ,10));
}
</script>
</body>
</html>
回答by Hyunsoo Kim
add step="any" to your input tag. if this does not work on your browser, change type to type="tel"
将 step="any" 添加到您的输入标签。如果这在您的浏览器上不起作用,请将类型更改为 type="tel"