previous page

 

next page

Lab 8/9 Conditionals

Implementing - validating

Now lets deal with entry problems. What if a user types in "noon" or "12 o'clock" or "12:35" rather than "12"? It's helpful to the user if the page spots that error and gives them feedback rather than just sitting there doing nothing.

So first let's define what we want them to enter: a number between 1 & 12

If they enter something else, we can help them out by telling them to "enter a number between 1 & 12".

Now that we've determined this, we need to write code that:

a. looks at what the user has entered
b. then figures out if it is not a number between 1 & 12, and,
c. if it is not, tells them to enter a number between 1 & 12

What has the user entered? You've already created a variable the contains the whatever the user entered: hours

To figure out if what the user entered is a number and is between 1 & 12, you need three tests:

is hours <1

is hours >12

is hours something other than a number? You can use the isNaN() function to test this - NaN stands for "Not a Number". Here are some examples: isNan(5) is false, while isNan("hello") is true.

You can actually write all three tests as one test that looks like this:

if (hours < 1 || hours > 12 || isNaN(hours))

The double vertical lines || means "or" so the code above says "if the hours variable holds a value that is less than one, or a value that is greater than 12 or the value is not a number) then...". In other words, if either the first, the second OR the third condition is true then...

 

1. Now start your if statement by copying the above line into your function (put it after the line where you create the hours variable, but before any lines that use the hours variable).

2. Add the opening and closing curly brackets for the if statement.

 

Let's look at what we're trying to write again:

a. looks at what the user has entered
b. then figures out if it is not a number between 1 & 12, and,
c. if it is not, tells them to enter a number between 1 & 12

We've done "a" and "b". Now you just need to do "c":

3. Inside the if statement (in other words, between the curly brackets), write a line that will create a popup box with the message "Enter a number between 1 & 12".

4. Save your file. Open it in a browser. Type a word or a number that is >13 or <1 into the entry box. Click on a time zone radio button and see if the message appears.

5. Return to the Catalyst WebQ and answer the next question.

 

 

Next, we'll try to make the page a little more user friendly

previous page   next page