Home > front end >  How to disable "-" and "e" from input field - html JS
How to disable "-" and "e" from input field - html JS

Time:08-17

I am working with php JS html. I have an input field with type number, and it represents a percentage, meaning 0.00 - 100.00. When I try to enter characters it is disabled by default, which is fine. However, when I try to enter "-" or "e", it is allowed to the user. I want it to be as the other chars meaning when pressing on the keyboard it should do nothing. This is my code of html:

<div  style="display: flex;"> 
   <input type="number" onkeydown="preventSomeKeys(event)"  name="fee_site_omp_percent" id="fee_site['omp_percent']" value="{{$fee_site['omp_percent'] ?? '0.00'}}"  step="0.1"  style="border:none;"> 
   <span >%</span>
</div>

this is the code in JS

function preventSomeKeys(event){
  var keyCode = event.key;
  console.log("keycode");
  console.log(keyCode);
  if(keyCode == "-"){ 
    console.log("BOOM");
     return false;
  }
  return
}

enter image description here

This is what is displayed on screen see "--" display.

This it the logs,

enter image description here

How I can prevent the user from entering these values "-", "e"?

CodePudding user response:

This is my solution that worked

<input type="number" onkeypress="preventSomeKeys(event)"   name="fee_site_omp_percent" id="fee_site['omp_percent']" value="{{$fee_site['omp_percent'] ?? '0.00'}}"  step="0.1"  style="border:none;"> 
               <span >%</span>                           

and this is the method that I created

function preventSomeKeys(event){
  var keyCode = event.key;
  console.log("keycode");
  console.log(keyCode);
  if(keyCode == "-"){ 
    console.log("BOOM");
    event.preventDefault();
     return false;
  }
  return
}

CodePudding user response:

Tried all of the above, the problem remains

The problem is your use of "old-school" event handler binding, via HTML attributes.

<input type="number" onkeydown="preventSomeKeys(event)"

It is not enough that your function returns false - you also still need to "pass on" this return value, from here:

onkeydown="return preventSomeKeys(event)"

CodePudding user response:

You can use a plugin to mask your input, so the user will not be able to enter these characters. For example, Inputmask. Scrolling down, you will also find how to use it. Here's the demo for you to understand how exactly input masking works (click 'Demo' button first). If the answer is not useful, or I didn't get your question right, feel free to point at that. All the best!

  • Related