0

Im using this code but it allows characters too. I only want the div to accept numeric value while function keys should work on it as well.

 this.shadowRoot.querySelector('div').addEventListener('keydown', async (e) => {
                if (e.keyCode >= 65 && e.keyCode <= 90) {
                    e.preventDefault();
                    return false;
                } 
            });
  • Have a look to https://stackoverflow.com/questions/1391278/contenteditable-change-events could be interesting for you mainly on the "keydown and keypress events are fired before the content itself is changed." fact – Alain BUFERNE Jun 19 '20 at 12:52

2 Answers2

1

Use an array to define the keys allowed, if you plan to use keycode, the array values should be ascii values. Key property can be used instead of keycode. Key property is a read only property which return the value of the key. You can refer to this article.

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key

allowedKeys = ['Backspace','Tab','Escape','Enter','1','2','3','4','5','6','7','8','9','0','ArrowLeft','ArrowRight','ArrowUp','ArrowDown','Delete']

this.shadowRoot.querySelector('div').addEventListener('keydown', async (e) => {
                if (!allowedKeys.includes(e.key)) {
                    e.preventDefault();
                    return false;
                } 
            });
Syed Jailani
  • 161
  • 5
0
<div><input type="number"></div>

edit: This essentially is the same thing if I don't wrap around input in the div. Setting the type attribute to number will only accept numbers. Wrapping it in a div tag doesn't really makes a difference in it by itself unless if you include js, id, class, or other tags inside the div tag.

Setting the input tag to number is a simple fix to your problem. Check the documentation here: https://www.w3schools.com/tags/att_input_type_number.asp

destroyer22719
  • 356
  • 2
  • 6
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Donald Duck Jun 19 '20 at 17:15