dedi wibisono
dedi wibisono

Reputation: 533

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.

Upvotes: 8

Views: 31956

Answers (5)

Nitin Garad
Nitin Garad

Reputation: 11

You can simply add condition for this block "0" from first character using --> event.target.value. Here is the following code for block "0" from first character.

Javascript.

     const handleOnchange =()=>{
       if(event.target.name === "myEvent"){
         event.target.value === event.targe.value.replace(/^0/, "");
      }
    }

HTML.

<input type="number" name="myEvent" id="myEvent" onChange={handleOnchange} />

Upvotes: 1

Pran R.V
Pran R.V

Reputation: 1158

Try

  if (event.target.value.length == 0 && event.which == 48) {
  return false;
   }

Upvotes: 1

Cristhoper
Cristhoper

Reputation: 11

$('#test').on("keypress",function (evt) {
   if (this.value.length == 1 && evt.which == 48 )
   {
      evt.preventDefault();
   }
});

Upvotes: 1

guest271314
guest271314

Reputation: 1

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">

Upvotes: 16

Sushanth --
Sushanth --

Reputation: 55750

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

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

Check Fiddle

Upvotes: 2

Related Questions