我试图让一个文本框只允许其中最多包含4个数字,并且如果有少于4个,则发出一个警告消息框。我已经设法通过使用此代码来完成此操作。
<tr>
<td id="ExamNumber">ExamNumber </td>
<td> <input type="text" name="ExamNumber" maxlength="4"
<font size="1">(Maximum characters: 4)</font> </td>
</tr>
if (document.ExamEntry.ExamNumber.value.length!=4) {
msg+="You must enter at least Four Numbers in the Examination Number \n";
document.ExamEntry.ExamNumber.focus();
document.getElementById('ExamNumber').style.color="red";
result = false;
}
然而,文本框的大小缩小,与代码中的其他文本框相比看起来很奇怪,并且它不是数字,只有文本字段中仍然允许使用字母和符号。请提前帮助并表示感谢。如果有帮助,完整的代码列表如下:
<head>
<title>Exam Entry Form</title>
<script language = "javascript" type = "text/javascript">
function validateForm() {
var result = true;
var msg="";
if (document.ExamEntry.name.value=="") {
msg+="You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value=="") {
msg+="You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
if (document.ExamEntry.ExamNumber.value=="") {
msg+="You must enter the Exam Number \n";
document.ExamEntry.ExamNumber.focus();
document.getElementById('ExamNumber').style.color="red";
result = false;
}
if (document.ExamEntry.ExamNumber.value.length!=4) {
msg+="You must enter at least Four Numbers in the Examination Number \n";
document.ExamEntry.ExamNumber.focus();
document.getElementById('ExamNumber').style.color="red";
result = false;
}
if(msg==""){
return result;
}
{
alert(msg)
return result;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border ="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="ExamNumber">ExamNumber </td>
<td> <input type="text" name="ExamNumber" maxlength="4"
<font size="1">(Maximum characters: 4)</font> </td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" onclick="return validateForm();" \></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
答案 0 :(得分:0)
在按键上使用以下代码仅允许使用数字键。对于文本框的宽度,请指定样式的宽度。
function NumericCharKeyPress()
{
if ((event.keyCode >= 48 && event.keyCode <= 57))
{
return true;
}
return false;
}
答案 1 :(得分:0)
使用此代码调整宽度:
<input type="text" maxlength="4" size="10" />
或
<input type="text" maxlength="4" style="width:100px;" />