2

I have written jquery for allowing numbers and dash - from being entered

$('.no-special-characters').keydown(function(e){  
  if (e.keyCode >= 48 && e.keyCode <= 57 || e.keyCode == 45) {
    return true; 
  }  else {
    return false;
  } 
});

It does not work accordingly. It allows only numbers to be accepted.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Nida
  • 1,672
  • 3
  • 35
  • 68
  • Just as a side note, if you want to control what's in an input, you should check characters instead of the keyboard event. Because there are ways to enter characters in an input without explicitly typing it, for example pasting in the input. – Kewin Dousse Sep 20 '17 at 11:00

4 Answers4

2

Try this

Updated with backspace support

Allow the keycode of 189

$('.no-special-characters').keydown(function(e) {
   var key =  e.keyCode|e.which;
      console.log(key) //check the key value in your console.log
      if (key >= 48 && key <= 57 || key == 45 || key == 189 ||key == 8){
          return true;
        } else {
          return false;
        }
      });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="no-special-characters">
Community
  • 1
  • 1
prasanth
  • 22,145
  • 4
  • 29
  • 53
2

try this code

$('.no-special-characters').keydown(function(e) {
  if (e.keyCode >= 48 && e.keyCode <= 57 || e.keyCode == 189) {
    return true;
  } else {
    return false;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="no-special-characters">
Bhargav Chudasama
  • 6,928
  • 5
  • 21
  • 39
1

Here you go with one more solution

$('.no-special-characters').keydown(function(e){  
  if ((e.keyCode >= 48 && e.keyCode <= 57) || e.keyCode == 189) {
    return true; 
  } else {
    return false;
  } 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="no-special-characters" type="text" />

Usually combine the keyCode from 48 to 57 & then the next keyCode condition.

Hope this will help you.

Shiladitya
  • 12,003
  • 15
  • 25
  • 38
0

e.keyCode = 109 is '-' on numpad

e.keyCode = 189 is '-' in alphabate keybord key on chrome

e.keyCode = 173 is '-' in alphabate keyboard key on firefox & on chrome 173 keycord is Mute On|Off

Source

Maybe this helps you, because using only e.keyCode == 189 (as some answers say) wont work in Firefox.

You can see, what keyCode your key presses return here: Link

Edit: You can also use regular expressions. Then there is no need to add keyCodes for different browsers:

$('.no-special-characters').keypress(function(e){  
    var txt = String.fromCharCode(e.which)
    var pattern = /^[0-9\-]+$/;
    if (!(pattern.test(txt) || e.keyCode == 8)){
            return false;
    }
})

JSFiddle

Community
  • 1
  • 1
drews
  • 146
  • 1
  • 8