0

The text area should accept only numbers, comma, arrow keys (keyboard), space, Ctrl+c, Ctrl+v, Ctrl+x, Ctrl+a and it should be in javascript only. Following is my code :

<textarea onkeypress=' return validateKey(event)'></textarea>
<body>
  <script type="text/javascript">
    function validateKey(e){
      var key= e.keyCode ? e.keyCode : e.charCode;
      console.log(key);
      if(key>47 && key <=57 || key>36 && key <=40 || key===44|| key===32 ||x|| key===8 || x|| key ===118 || key==99 || key === 120){
        return true;
      }
      return false;
    }
  </script>
</body>

it works fine with chrome but in firefox, it takes the same keycode for 'a' and ctrl+a or cmd+a (mac) and so on for cut, paste, copy.

Is there any way in which i can treat ctrl+a and 'a' are two diff characters.

kyun
  • 9,710
  • 9
  • 31
  • 66
Sharad Pawar
  • 290
  • 1
  • 2
  • 16

2 Answers2

0

Just add a if (!e.ctrlKey) outside your other if. This will prevent it from running if the control key is being pressed.

yaakov
  • 4,568
  • 4
  • 27
  • 51
0

I have found the way for this validation

<!DOCTYPE html>
<html>
<head>
 <title>Task</title>
</head>
<body>
 <textarea style="width: 300px;height: 100px" onkeypress=' return validateKey(event)'></textarea>

 <script type="text/javascript">
  function validateKey(e) {
    var key = e.keyCode ? e.keyCode : e.charCode;
    console.log(key);
    if (key > 47 && key <= 57||(key > 36 && key <= 40) && !e.shiftKey || key === 44 || key == 17 || key === 32 || key === 8 || (key == 97 && e.ctrlKey) || (key == 120 && e.ctrlKey) || (key == 99 && e.ctrlKey) || (key == 118 && e.ctrlKey) || e.metaKey) {
        return true;
    }
    return false;
}
 </script>
</body>
</html>
Sharad Pawar
  • 290
  • 1
  • 2
  • 16