user15089140
user15089140

Reputation:

How to add a keypress event listener into my dynamically created input text field in javascript?

I want to add a keypress listener to my input text field. This is my code:

var input = document.createElement("input");
input.type = "text";
input.id="vac";
input.addEventListener("keypress",(e) => {return IsAlphaNumeric(e);});

function IsAlphaNumeric(e) { //prohibits input of all special characters except for `/`
  var specialKeys = new Array();
  specialKeys.push(8);  //Backspace
  specialKeys.push(9);  //Tab
  specialKeys.push(46); //Delete
  specialKeys.push(36); //Home
  specialKeys.push(35); //End
  specialKeys.push(37); //Left
  specialKeys.push(39); //Right
  var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
  var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));

  if(e.charCode==47){
      ret=true;
  }
  return ret;
}

Now when I execute the code, the keypress listener is not working. What is wrong? How do I fix this?

Upvotes: 0

Views: 1908

Answers (1)

Ernesto Stifano
Ernesto Stifano

Reputation: 3130

If you want to prevent non alpha-numerical characters, with the exception of /, this is the modern way to go. Use event.preventDefault(). And a simple RegExp is enough for string testing.

const input = document.createElement('input');

input.type = 'text';
input.id = 'vac';

const shouldPrevent = (str) => !/[a-zA-Z\u00C0-\u00FF\d\/]/.test(str);

input.addEventListener('keydown', (e) => {
    if (shouldPrevent(e.key) && e.cancelable) {
        e.preventDefault();
    }
});

document.getElementById('root').appendChild(input);
<div id="root"></div>

Upvotes: 2

Related Questions