我只是GCSE級別,我需要在我的代碼中只有4個字符的文本框。我已經使它最多爲4,但我需要它至少有4。我也讓它只接受數字。我沒有在我的學校使用HTML 5。如何使用Javascript在HTML文本框上設置最小和最大字符長度
這是我的全部代碼:
<head>
<title>Exam entry</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 your exam number. \n";
document.ExamEntry.ExamNumber.focus();
document.getElementById('ExamNumber').style.color="red";
result = false;
}
if(document.ExamEntry.ExamNoLen.value.length <4) {
msg+="Your eaxm nuber must be 4 digits long. \n";
document.ExamEntry.ExamNumber.focus();
document.getElementById('ExamNumber').style.color="red";
result = false;
}
checkInput(elem){
if(elem.value.length != 4){
alert("This value needs to be 4 characters long!");
elem.value = ""; // Reset the textbox
}
else{
alert("This value is 4 characters long.");
}
}
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">Exam Number </td>
<td>
<input name="ExamNumber" type="text"
onkeydown="return (event.ctrlKey || event.altKey
|| (47<event.keyCode && event.keyCode<58 && event.shiftKey==false)
|| (95<event.keyCode && event.keyCode<106)
|| (event.keyCode==8) || (event.keyCode==9)
|| (event.keyCode>34 && event.keyCode<40)
|| (event.keyCode==46))"
maxlength="4" onblur="checkInput(this)" />
</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>
我還使用Dreamweaver編輯代碼。 – user1990084