I want to prevent 0 as the first character. But when I focusout and focusin again, then I add "2" in the first, it still run, I want should not run.
我想阻止0作为第一个字符。但是当我再次聚焦和焦点时,我在第一个中添加“2”,它仍然运行,我想不应该运行。
Here is my HTML
这是我的HTML
<input type="number" id="test">
My JS
我的JS
$('#test').keypress(function(evt) {
if (evt.which == "0".charCodeAt(0) && $(this).val().trim() == "") {
return false;
}
});
Anybody help or suggest what should I do? Thank you.
有人帮忙或建议我该怎么办?谢谢。
2 个解决方案
#1
3
You can use input
event, which also handles pasted values, String.prototype.replace()
with RegExp
/^0/
to replace all 0
characters found within .value
of element
你可以使用输入事件,它也处理粘贴的值,String.prototype.replace()和RegExp / ^ 0 /来替换在元素的.value中找到的所有0个字符
$("#test").on("input", function() {
if (/^0/.test(this.value)) {
this.value = this.value.replace(/^0/, "")
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input type="number" id="test">
#2
1
Compare which
property with the ASCII code of number 0
and return false.
将哪个属性与数字0的ASCII代码进行比较并返回false。
if (evt.which === 48) {
return false;
}
检查小提琴
#1
3
You can use input
event, which also handles pasted values, String.prototype.replace()
with RegExp
/^0/
to replace all 0
characters found within .value
of element
你可以使用输入事件,它也处理粘贴的值,String.prototype.replace()和RegExp / ^ 0 /来替换在元素的.value中找到的所有0个字符
$("#test").on("input", function() {
if (/^0/.test(this.value)) {
this.value = this.value.replace(/^0/, "")
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input type="number" id="test">
#2
1
Compare which
property with the ASCII code of number 0
and return false.
将哪个属性与数字0的ASCII代码进行比较并返回false。
if (evt.which === 48) {
return false;
}
检查小提琴