2

对于我的研究,我需要创建一个简单的脚本来检查输入的数据(假设是 5 位数的邮政编码)是否实际上有 5 位数。如果输入的数字多于或少于 5 个,则应弹出警报。

到目前为止,我设法获得了多于和少于 5 位数字的警报,但即使输入 5 位数字,警报也会出现。

由于 js 不是我最喜欢的主题,我迷路了,即使它似乎是一件简单的事情。

提前感谢您的答案和提示。

<script type="text/javascript"> 
<!--
function CheckZip ()
{
var content = document.forms['zipfield'].Field.value;
var length = content.length;
if (length >=5) (alert('Please enter a 5 digit zip code!'));
else if (length <=5) (alert('Please enter a 5 digit zip code!'));
else (length ==5) (alert('Valid entry'))
}
//-->
</script> 
</head> 
<body>  
<div align="left">
<p>Please enter a 5 digit zip code</p> 
<form name="zipfield" action="post"><input name="Field" size="5">
<br />
<br />
<input name="check" value="Check entry" onclick="CheckZip()" type="submit"> 
</form>
4

4 回答 4

3

Check your condition..

When length is 5 it will go to the first if statemenet because you have specified it to be >= 5

So when length is 5 , it will never hit the statement else (length ==5)

if (length >5) {
      alert('Please enter a 5 digit zip code!')
}
else if (length <5) {
    alert('Please enter a 5 digit zip code!')
}
else (length ==5) {
     alert('Valid entry')
};

Better

if( length === 5){
   alert('Valid entry');
}
else{
   alert('Please enter a 5 digit zip code!');
}

Check Fiddle

You have other syntax errors in your script

if (length >=5) (alert('Please enter a 5 digit zip code!'));
              --^-- Supposed to be {                    --^-- supposed to be }

Also you are ending the if loop with a semicolon ; .. Need to remove that .. Otherwise the statement in else if and else will never be executed

于 2012-11-13T21:07:00.320 回答
3

How about this:

if (content.length !== 5) {

   alert('Please enter a 5 digit zip code!');

} else {

   alert('Valid entry');
}
于 2012-11-13T21:07:24.640 回答
2

5 is greater than or equal to 5, so the error alert will come up.

You should be using > and <, instead of >= and <=.

于 2012-11-13T21:07:11.603 回答
2

>= means greater than or equal to, <= means less than or equal to. Your problem is that if your input is exactly 5 characters long then:

if (length >=5) 

Will evaluate as true, and you won't get to your else statement.

于 2012-11-13T21:07:38.573 回答