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.
Here is my HTML
<input type="number" id="test">
My 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.
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
$("#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">