日期:2014-05-18  浏览次数:20672 次

JS控制文本框
1:JS如何控制让文本框内只能输入数字?(求最佳答案)
2:JS如何控制让文本框内只能输入字母?(求最佳答案)


------解决方案--------------------
HTML code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>烦人的IE6</title>
<script type="text/javascript">
function HandleKeyDown(e){
    var evt=e||window.event;
    var srcEl=evt.target||evt.srcElement;
    var nKeyCode=evt.which||evt.keyCode;
    var sValue=srcEl.value+String.fromCharCode(nKeyCode);
    var oRegInt=/^[1-9]\d*$/;

    switch(nKeyCode){
        case 8://退格
        case 46://删除
            return true;
        default:
            return oRegInt.test(sValue);    
    }
}
</script>
</head>
<body>
只能输入整数:
<input type="text" id="txt1" name="txt1" onkeydown="return HandleKeyDown(event);"/>
</body>
</html>

------解决方案--------------------
1. 仅为数字,添加如下事件:
onkeyup="value=value.replace(/[^\d]/g,'');"
2. 仅为字母,添加如下事件:
onkeyup="value=value.replace(/[^\a-zA-Z]/g,'');"


------解决方案--------------------
<HTML><HEAD></HEAD>
<BODY bgcolor="#66CC66"><Font size=2><CENTER>
<script LANGUAGE="javascript" type="text/javascript">
function check()
{

if (document.form1.userid.value == "")
{
alert("请填写您数字!");
document.form1.userid.focus();
return false;
}
var filter=/[^\d]/g,";
;
if (!filter.test(document.form1.userid.value)) {
alert("这里必须输入数字");
document.form1.userid.focus();
document.form1.userid.select();
return false;
}

if (document.form1.password.value=="")
{
alert("请填写您的字母!");
document.form1.password.focus();
return false;
}
var filter=/[^\a-zA-Z]/g,'';
if (!filter.test(document.form1.password.value)) {
alert("这里必须输入字母");
document.form1.password.focus();
document.form1.password.select();
return false;
}
 document.form1.submit();
}
</script>
<FORM action="helpRegister" method = post name="form1" >
<table>
<tr><td>数字:</td><td><Input type=text name="userid" ></td></tr>
<tr><td>字母:</td><td><Input type=password name="password"></td></tr>
</table>
<table>
<tr><td><Input type=reset name="c" value="重置"></td>
<td><Input type=button name="g" value="提交" onClick="check()"></td></tr>
</table>
</Form>

</CENTER>
</Body></HTML>


看看这样行吗?