rollindice
rollindice

Reputation: 29

Java Script issue

For my studies I need to create a simple script that checks if the entered data (suppose to be a 5 digit zip code) actually has 5 digits. If more or less then 5 digits entered, a alert should pop up.

So far I managed to get the alert for more and less then a 5 digit entry, but even when entering 5 digits, the alert will come up as well.

Since js is not my favourite subject I am lost, even tho it seems to be a simple thing.

Thanks in advance for answers and hints.

<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>

Upvotes: 1

Views: 83

Answers (4)

Sushanth --
Sushanth --

Reputation: 55750

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

Upvotes: 3

Matt Burland
Matt Burland

Reputation: 45155

>= 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.

Upvotes: 2

frenchie
frenchie

Reputation: 52047

How about this:

if (content.length !== 5) {

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

} else {

   alert('Valid entry');
}

Upvotes: 3

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324810

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

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

Upvotes: 2

Related Questions