我正在尝试制作一个文本框,其中最多只允许 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>