Disable some characters from input field
with JQuery,
$("input").keypress( function(e) {
var chr = String.fromCharCode(e.which);
if ("12345NOABC".indexOf(chr) < 0)
return false;
});
without JQuery
document.getElementById("foo").onkeypress = function(e) {
var chr = String.fromCharCode(e.which);
if ("12345NOABC".indexOf(chr) < 0)
return false;
};
For one liners, from @mplungjan and @matthew-lock's comment
document.querySelector("#foo").onkeypress = function(e) {
return "12345NOABC".indexOf(String.fromCharCode(e.which)) >= 0;
};
It's not 100% clear whether you want to restrict the form being submitted with invalid values, or literally prevent the user from even typing those values. The other answers deal with the latter, and I think that is what you meant, but there will be people arriving here (like me) who just want to prevent form submission.
In which case:
Use the pattern
attribute on the input
element:
<input pattern="[REGEX HERE]">
https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation
https://regex101.com/
Try this
$(function(){
$('#txt').keypress(function(e){
if(e.which == 97 || e.which == 98 || e.which == 99 || e.which == 110 || e.which == 111 || e.which == 65 || e.which == 66 || e.which == 67 || e.which == 78 || e.which == 79 || e.which == 49 || e.which == 50 || e.which == 51 || e.which == 52 || e.which == 53){
} else {
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='txt' value='' onpaste="return false" />
Update 9th March 2018
$(function(){
$('#txt').keypress(function(e){
// allowed char: 1 , 2 , 3, 4, 5, N, O, A, B, C
let allow_char = [97,98,99,110,111,65,66,67,78,79,49,50,51,52,53];
if(allow_char.indexOf(e.which) !== -1 ){
//do something
}
else{
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='txt' value='' onpaste="return false" />
Update 25th November 2020
let textarea = document.getElementById('txt');
textarea.addEventListener('keydown', (e) => {
if(['1','2','3','4','5', 'N', 'O', 'A', 'B', 'C'].indexOf(e.key) !== -1){
// do something
} else {
e.preventDefault();
}
});
CodePen Demo