我發現一些類似的說明,但沒有幫助,它們都是用於特殊字符或數字。禁用輸入字段中的某些字符
我只需要使用戶類型只有1,2,3,4,5,N,O,A,B,C。所有其他角色都應該受到限制。
任何方式,我可以讓我自己選擇限制/允許的字符輸入?
- 不是很熟悉javascript。
我發現一些類似的說明,但沒有幫助,它們都是用於特殊字符或數字。禁用輸入字段中的某些字符
我只需要使用戶類型只有1,2,3,4,5,N,O,A,B,C。所有其他角色都應該受到限制。
任何方式,我可以讓我自己選擇限制/允許的字符輸入?
試試這個
$(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" />
更新2018年3月9日
$(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" />
與jQuery,
$("input").keypress(function(e) {
var chr = String.fromCharCode(e.which);
if ("12345NOABC".indexOf(chr) < 0)
return false;
});
不JQuery的
document.getElementById("foo").onkeypress = function(e) {
var chr = String.fromCharCode(e.which);
if ("12345NOABC".indexOf(chr) < 0)
return false;
};
對於一個襯墊,從@mplungjan和@馬修鎖的評論
document.querySelector("#foo").onkeypress = function(e) {
return "12345NOABC".indexOf(String.fromCharCode(e.which)) >= 0;
};
或'return「12345NOABC」.indexOf(chr)> = 0;'如果你喜歡oneliners – mplungjan 2013-02-11 05:58:44
@mplungjan,很好的電話 – allenhwkim 2013-02-11 15:05:48
甚至'返回「12345NOABC」.indexOf(String.fromCharCode(e.which))> = 0;'把它減少到一行 – 2014-10-29 03:03:39
如果要禁用從輸入領域的幾個字符,你可以做這樣的事情:
<input type="text" onkeydown="return (event.keyCode!=86);"/>
86是V.的代碼檢查以下鏈接中其他鍵的代碼。
https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
這與[Pragnesh Chauhan的回答](https://stackoverflow.com/a/14806389/3789665)有何不同? – greybeard 2017-05-28 15:59:44
'所有的人都對任何特殊字符或digits.'你就不能修改代碼,而非只是一味的複製和粘貼? – nhahtdh 2013-02-11 05:07:22
使用http://archive.plugins.jquery.com/project/limitkeypress – DON 2013-02-11 05:09:42
limitkeypress的新鏈接http://brianjaeger.com/process.php – 2014-10-29 03:01:44