Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable some characters from 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.

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

  • Not very familiar with javascript.
like image 589
Nutic Avatar asked Feb 11 '13 05:02

Nutic


People also ask

How do I restrict the input field of a character?

The HTML <input> tag is used to get user input in HTML. To give a limit to the input field, use the min and max attributes, which is to specify a maximum and minimum value for an input field respectively. To limit the number of characters, use the maxlength attribute.


2 Answers

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; }; 
like image 73
allenhwkim Avatar answered Sep 24 '22 22:09

allenhwkim


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

like image 40
Pragnesh Chauhan Avatar answered Sep 21 '22 22:09

Pragnesh Chauhan