0

There's anyway to merge the elements of javascript to decrease the code size?

<form>
   <input id="input1" type="text"/>
   <input id="input2" type="text"/>
</form>

//javascrypt
document.getElementById("input1").onkeypress = function(e) {
   var chr = String.fromCharCode(e.which);
   if ("1234567890qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM".indexOf(chr) < 0) return false;
};
document.getElementById("input2").onkeypress = function(e) {
   var chr = String.fromCharCode(e.which);
   if ("1234567890qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM".indexOf(chr) < 0) return false;
};
  • Name the function and reuse it? – evolutionxbox Dec 17 '20 at 12:35
  • You could select by "class" as opposed to "id". – GetSet Dec 17 '20 at 12:35
  • 1
    `document.querySelectorAll("#input1, #input2")` will give you a `NodeList` containing both of them. But note that it's a *list*, so you'd have to loop through it to assign that handler ([more here](http://stackoverflow.com/questions/10693845/what-do-queryselectorall-getelementsbyclassname-and-other-getelementsby-method)). – T.J. Crowder Dec 17 '20 at 12:37

1 Answers1

2

Yes you can reduce the size by creating an event handler and use that event handler in both cases,

<form>
   <input id="input1" type="text"/>
   <input id="input2" type="text"/>
</form>

//javascrypt

const keyPressHandler = (e) => {
   var chr = String.fromCharCode(e.which);
   if ("1234567890qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM".indexOf(chr) < 0) return false;
};

document.getElementById("input1").onkeypress = keyPressHandler;
document.getElementById("input2").onkeypress = keyPressHandler;
Md Sabbir Alam
  • 4,937
  • 3
  • 15
  • 30