Home > Enterprise >  Disabling space as first character in input field doesnt work on Chrome Android/App
Disabling space as first character in input field doesnt work on Chrome Android/App

Time:10-11

I have this code that basically disables adding in an empty space inside an input field, however it doesn't seem to run on Chrome Mobile/App/Android.

Does anyone have any solutions?

<script>
document.getElementById('firstname').addEventListener('keydown', function(evt){
  if (this.value.length === 0 && evt.which === 32) evt.preventDefault();
});
</script>

CodePudding user response:

According to https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent, KeyboardEvent.which is deprecated. Use KeyboardEvent.key instead.

Also see list of key codes.

document.getElementById('firstname').addEventListener('keydown', function(evt){
  if (this.value.length === 0 && evt.key === " ") evt.preventDefault();
});
<input id="firstname">

CodePudding user response:

You can use KeyboardEvent.code instead

document.getElementById('firstname').addEventListener('keydown', function(evt){
  if (this.value.length === 0 && evt.code === 'Space') 
    evt.preventDefault();
});
<input id="firstname">

  • Related