javascriptjqueryhtml

How to disable all but 10 specific characters from an input field


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.

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


Solution

  • 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