簡體   English   中英

我正在嘗試使一個文本框只能包含4位數字

[英]I am trying to make a text box only be able to have 4 Digits within it

我試圖使一個文本框內最多允許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>

在按鍵上使用以下代碼僅允許數字鍵。 對於文本框的寬度,請在樣式中指定寬度。

function NumericCharKeyPress()
{
if ((event.keyCode >= 48 && event.keyCode <= 57))
{
    return true;
}
return false;

}

使用此代碼調整寬度:

<input type="text" maxlength="4" size="10" />

要么

<input type="text" maxlength="4" style="width:100px;" />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM