在撰寫web系統有時需要限制欄位
只能key 英文 或 數字,
而不給key中文,符號的可怕需求...
這邊提供從大學同學阿勇多年經驗的code...XD
========jsp中的input 欄位 兩個事件都要有============
<input onkeydown="divChian();" onkeypress="LimitInput('Num',false);" type="”text”" />
//divChian() 擋中文
//LimitInput('Num',false) 選擇只能輸入數字, 且不轉換成大寫(若為英文)
===============javascript==============
//擋中文
function divChian(){
var LOBJ_Lable = window.event;
if(LOBJ_Lable.keyCode == 229) //中文都會有299這個code
event.returnValue=false;
}
//LimitInput[參數,控制的物件,是否要轉大寫(true:要轉;false:不要轉)]
function LimitInput(LSTR_Type,LBOL_Chagecode){
var LOBJ_Lable = window.event;
//轉大寫;
if (LBOL_Chagecode==true){
if (LOBJ_Lable.keyCode >= 97 && LOBJ_Lable.keyCode<= 124){
LOBJ_Lable.keyCode-=32;
}
}
switch (LSTR_Type){
//只能輸入英數
case "NumEng":
if ( (LOBJ_Lable.keyCode >= 48 && LOBJ_Lable.keyCode<= 57)||
(LOBJ_Lable.keyCode >= 65 && LOBJ_Lable.keyCode<= 90)||
(LOBJ_Lable.keyCode >= 97 && LOBJ_Lable.keyCode<= 122)){
return LOBJ_Lable.keyCode;
}else{
return LOBJ_Lable.keyCode =0;
}
break;
case "Num":
if(LOBJ_Lable.keyCode < 48 || LOBJ_Lable.keyCode > 57){
LOBJ_Lable.keyCode = 0;
}
break;
case "NumDotMinus":
if ((LOBJ_Lable.keyCode >= 48 && LOBJ_Lable.keyCode<= 57)||
(LOBJ_Lable.keyCode == 45 || LOBJ_Lable.keyCode == 46)){
return LOBJ_Lable.keyCode;
}else{
return LOBJ_Lable.keyCode =0;
}
break;
}
}