Reputation: 1702
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.
Upvotes: 2
Views: 3886
Reputation: 146
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
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;
}
})
Upvotes: 0
Reputation: 22510
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">
Upvotes: 2
Reputation: 12161
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.
Upvotes: 1
Reputation: 7171
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">
Upvotes: 2