Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
82
rated 0 times [  88] [ 6]  / answers: 1 / hits: 70244  / 12 Years ago, mon, february 11, 2013, 12:00:00

I have found some instructions similar, but none helps, all of them are either for special chars or for digits.



I need to make user type only 1 , 2 , 3, 4, 5, N, O, A, B, C . all other characters should be restricted.



Any way I can make my own selection of restricted/allowed chars for inputs ?




  • Not very familiar with javascript.


More From » jquery

 Answers
17

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


[#80304] Saturday, February 9, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
piper

Total Points: 734
Total Questions: 93
Total Answers: 112

Location: Burundi
Member since Wed, Apr 6, 2022
2 Years ago
;