Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent a "0" as the first character when typing in input type number?

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.

like image 515
dedi wibisono Avatar asked Dec 06 '16 01:12

dedi wibisono


2 Answers

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">
like image 167
guest271314 Avatar answered Oct 29 '22 23:10

guest271314


Compare which property with the ASCII code of number 0 and return false.

if (evt.which === 48) {
  return false;
}

Check Fiddle

like image 35
Sushanth -- Avatar answered Oct 29 '22 22:10

Sushanth --