I would like to limit a positive integer or 0. So I wrote this code:
我想限制一个正整数或0.所以我写了这段代码:
<input type="text" name="age" id="age" value="${po.age}"
onkeyup="value=value.replace(/[^[1-9]\d*|0]/g,'')"
style="ime-mode:disabled;" onpaste="return false;"
/>
But I find that I can only input 1-9. If I input 0, it will be removed. How to fix it?
但我发现我只能输入1-9。如果我输入0,它将被删除。怎么解决?
5 个解决方案
#1
3
You can just use a input of type number
and set a min
value to 0:
您只需使用类型编号的输入并将最小值设置为0:
Try me:
<input type="number" min="0">
#2
2
You can try this:
你可以试试这个:
<input type="text" name="age" id="age" value="${po.age}" onkeyup="value = value.replace(/[a-z]|-/gi, ''); value = parseInt(value.match(/\d+|\./gi).join('')) || '';" style="ime-mode:disabled;" onpaste="return false;"
/>
https://jsfiddle.net/2vamj5w0/
https://jsfiddle.net/2vamj5w0/
#3
1
Simply you can write the regular expression like this, if your need is any digit followed by a zero
如果您需要任何数字后跟零,您只需编写这样的正则表达式即可
/[1-9]\d*[0]{1}/
/ [1-9] \ d * [0] {1} /
#4
0
Just change in your code value=value.replace(/[^[1-9]\d*|0]/g,'')
to value=value.replace(/[^[0-9]\d*/g,'')
so it will looks like
只需将代码值= value.replace(/ [^ [1-9] \ d * | 0] / g,'')更改为value = value.replace(/ [^ [0-9] \ d * / g,'')所以它看起来像
<input type="text" name="age" id="age" onkeyup="value=value.replace(/[^[0-9]\d*/g,'')" style="ime-mode:disabled;" onpaste="return false;" />
Alternative you can try this
另外你可以尝试这个
<input name="number" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')">
#5
0
Can you use something like this :
你能用这样的东西:
value=isNaN(parseInt(value,10))?"":parseInt(value,10)<0?"":parseInt(value,10)
#1
3
You can just use a input of type number
and set a min
value to 0:
您只需使用类型编号的输入并将最小值设置为0:
Try me:
<input type="number" min="0">
#2
2
You can try this:
你可以试试这个:
<input type="text" name="age" id="age" value="${po.age}" onkeyup="value = value.replace(/[a-z]|-/gi, ''); value = parseInt(value.match(/\d+|\./gi).join('')) || '';" style="ime-mode:disabled;" onpaste="return false;"
/>
https://jsfiddle.net/2vamj5w0/
https://jsfiddle.net/2vamj5w0/
#3
1
Simply you can write the regular expression like this, if your need is any digit followed by a zero
如果您需要任何数字后跟零,您只需编写这样的正则表达式即可
/[1-9]\d*[0]{1}/
/ [1-9] \ d * [0] {1} /
#4
0
Just change in your code value=value.replace(/[^[1-9]\d*|0]/g,'')
to value=value.replace(/[^[0-9]\d*/g,'')
so it will looks like
只需将代码值= value.replace(/ [^ [1-9] \ d * | 0] / g,'')更改为value = value.replace(/ [^ [0-9] \ d * / g,'')所以它看起来像
<input type="text" name="age" id="age" onkeyup="value=value.replace(/[^[0-9]\d*/g,'')" style="ime-mode:disabled;" onpaste="return false;" />
Alternative you can try this
另外你可以尝试这个
<input name="number" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')">
#5
0
Can you use something like this :
你能用这样的东西:
value=isNaN(parseInt(value,10))?"":parseInt(value,10)<0?"":parseInt(value,10)