javascript conditional statements

69
Javascript Conditional Statements To write more complex programs in any language, you need something called control flow. If Statement If statements are the backbone of programming. To get you started on just what an If statement is, type this code into the HEAD section of a HTML page, then test it out: <SCRIPT language = "JavaScript"> ConfirmStatus = confirm("are u member of siliconindia?") if (ConfirmStatus == true) { alert("Yes, I am.") } </SCRIPT> The first line of code is what gives you a new type of message box -confirm. It looks like this in Internet Explorer. The programme then waits until you click either the OK button or the Cancel button. ConfirmStatus = confirm("are u member of siliconindia?") Whichever button you click, the answer will be stored in the variable ConfirmStatus. The answer, in this case, is a Boolean value: it's either True or False.

Upload: venkatesh-vuruthallu

Post on 22-Oct-2014

132 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Javascript Conditional Statements

Javascript Conditional Statements

To write more complex programs in any language, you need something called control flow.

If Statement

If statements are the backbone of programming. To get you started on just what an If statement is, type this code into the HEAD section of a HTML page, then test it out:

<SCRIPT language = "JavaScript">ConfirmStatus = confirm("are u member of siliconindia?")if (ConfirmStatus == true) {alert("Yes, I am.")}

</SCRIPT>

The first line of code is what gives you a new type of message box -confirm. It looks like this in Internet Explorer.

The programme then waits until you click either the OK button or the Cancel button.

ConfirmStatus = confirm("are u member of siliconindia?")

Whichever button you click, the answer will be stored in the variable ConfirmStatus. The answer, in this case, is a Boolean value: it's either True or False.

You do the testing with an if statement. Our if statement was as simple as if statement get. It was this:/p>

if (ConfirmStatus == true) {alert("Yes I am. ")}

Note the format for an if statement:

if (condition to test) {

Page 2: Javascript Conditional Statements

Your statement here

}

In our condition to test, we wanted to check whether the variable ConfirmStatus was true or false. So we did this:

ConfirmStatus == true

We're saying "If ConfirmStatus has a value of true" then execute the next line of code.

The main point is that you would only get the alert message IF you clicked the OK button. Because then the variable ConfirmStatus would be true. But what if the user clicked Cancel? What happens then?

If the Cancel button is clicked, the ConfirmStatus variable will be false. In that case, our alert box statement doesn't get executed - the programme will just ignore that line and move on to the next line of code.

We can, however, add another statement to check for a false condition. Change your code to this:

<SCRIPT language = JavaScript>

ConfirmStatus = confirm("did u registered with Siliconindia?")

if (ConfirmStatus == true) {

alert("Yes I already registered. ")

}

if (ConfirmStatus == false) {

alert("NO, not yet registered.")

}

</SCRIPT>

"If it's true, do one thing; if it's false do another thing"

Page 3: Javascript Conditional Statements

if … else statements

We saw in the last part of this Control Flow section that to test two conditions (true and false) two if statements were needed. But you don't have to use separate if statements. Instead, you can use the else word. This is ideal for Boolean values. Here's our code again, this time with an if … else statement.

ConfirmStatus = confirm("did u registered with Siliconindia?")

if (ConfirmStatus == true) {

alert("Yes I already registered. ");

}

else {

alert("NO, not yet registered.");

}

The format for an if … else statement is this:

if (condition to test) {

Statement 1

}else {

Statement 2

}

So if the first statement isn't true, the code beneath else gets executed.

if … else if statements

If you need multiple if statements, then if … else if is the one to use.

We  need a few more symbols to work with. You've already met the double equals symbol (==),

Page 4: Javascript Conditional Statements

and know that this means "has a value of".

Here we have some more symbol: >, <, <=, >=, !=, &&, ||

We'll see how these operators work with our next programme. So design an HTML page with the following form on it.

<FORM NAME = "AgeTest">

Type in your age, then click the button:<INPUT TYPE = Text NAME = txtAge Size = 15><INPUT TYPE = Button NAME = "b1" VALUE = "Age Tester" onClick = message()>

</FORM>

Once you've typed the HTML code for the form, type this JavaScript code in the HEAD section of your page:

<SCRIPT language = "javascript">

function message() {

age = document.AgeTest.txtAge.value

if (age < 16) {

alert("How's school these days?")

}else if(age > 16) {

alert("It's tough being an adult")

}}

</SCRIPT>

We had another onClick event for our command button, which called the message( ) function. When the message( ) is called, it first stores the value in the text box into a variable called age.

Page 5: Javascript Conditional Statements

age = document.AgeTest.txtAge.value

Next, we need to test what is inside the age variable. We started the test with an if statement:

if (age < 16) {

alert("How's school these days?")

}

Next, because we're checking for multiple values, we have the else if condition. Ours was this:

if (age < 16) {

alert("How's school these days?")

}else if(age > 16) {

alert("It's tough being an adult")

}The format for the else if part is this:

if (condition to test) {

statement 1

}else if(condition to test) {

statement 1

}

After all, somebody might type text into your text box, or minus numbers, or nothing at all. In which case, this could solve your problems (though it's no substitute for more thorough error checking):

if (age < 16) {

Page 6: Javascript Conditional Statements

alert("How's school these days?")

}else if(age > 16) {

alert("It's tough being an adult")

}else {

alert("Please try again")

}

The Operators, And, Or

Exercise

Add a few more else if statements, and test for these ages groups:

17 to 2526 to 4041 to 6566 and over

Add a suitable alert message, when the command button is clicked.

With an exercise like the one above, it's really handy to use the AND operator (&&) and the OR operator ( || ). Here's how to use them.

 

AND and OR

These two operators will return a Boolean value. You use them when you want to test two or more conditions.

 

If BOTH conditions are true then the IF Statement is true. If just one of them is false, then the entire IF Statement is false. Note the format:

Page 7: Javascript Conditional Statements

if (condition1 && condition2) {

Code if true here

}

Contrast that with the OR operator, if one of your conditions is true then the entire IF statement is true:

if (condition1 || condition2) { Code if true here }

Not a Number

Let's use the AND operator to solve our little problem from a previous lesson. if a user enters text into our text boxes, then we get the "NaN" error message in our answer text box. Click the Add Numbers button and see what happens:

What we need to do is to check the text in the text box. If they are both numbers, then we can go ahead and add them up; if one of them isn't, then we can display an alert box to tell the user to try again. Our original code was this:

<SCRIPT LANGUAGE = "javascript"> A = document.frmOne.txtFirstNumber.valueB = document.frmOne.txtSecondNumber.valueA = Number(A)B = Number(B)C= A + Bdocument.frmOne.txtThirdNumber.value = C</SCRIPT>

We can insert an If statement on the third line of the code which will check if the user entered a number. Only then will we do the adding up. The if statement we can use is this:

if (Number(A) && Number(B)) { A = Number(A)B = Number(B)C = A + Bdocument.frmOne.txtThirdNumber.value = C }else { alert("Please enter a number in both boxes") }

Page 8: Javascript Conditional Statements

JavaScript Loops

Loops execute a block of code a specified number of times, or while a specified condition is true. A loop is something that goes round and round. You also need to tell the programme two other things - where to start your loop, and what to do after it's finished one lap (known as the update expression).

There are three types of loops in JavaScript:

for loopswhile loopsdo … while loops.

We'll start with the most common type - the for loop.

For LoopsLoops through a block of code a specified number of times.

The format for a for loop is this:

for (start value; end value; update expression) {code to be executed.}

Example:counter = 0for(start = 1; start < 10; start++) {counter = counter + 1document.write("start = " + start + " counter = " + counter + "<BR>")}

Result:start = 1 counter = 1start = 2 counter = 2start = 3 counter = 3start = 4 counter = 4start = 5 counter = 5start = 6 counter = 6

Page 9: Javascript Conditional Statements

start = 7 counter = 7start = 8 counter = 8start = 9 counter = 9start = 10 counter = 10

 

Start ValueThe first condition is where you tell JavaScript the initial value of your loop. In other words, initial point of the loop. We used this:start = 1

End ValueNext, you have to tell JavaScript when to end your loop. This can be a number, a Boolean value, a string, etc.

Update ExpressionLoops need a way of getting the next number in a series. In other words, you need to tell the loop how it is to go round and round. We used this:

start++

In the javaScript programming language the double plus symbol (++) means increment (increase the value by one). It's just a short way of saying this:

start = start + 1

JavaScript While and Do Loops

While LoopsLoops through a block of code while a specified condition is true.The structure of a while loop is more simple than a for loop, in case of while loop we are evaluating  only one condition. The loop goes round and round while the condition is true. When the condition is false, the programme breaks out of the while loop. Here's the syntax for a while loop:

while (condition) {statement}

And here's some code to try. All it does is increment a variable called counter:

Page 10: Javascript Conditional Statements

counter = 1while (counter < 11) {document.write(" counter = " + counter + "<BR>")counter++}

here is table programme again, only now we've used a while loop instead of a for loop (the lines that write the result to the text area have been left out):start = 1end = 1times = 2answer = 0while (end < 11) {answer = start * timesstart++end++}

while loop calculates the time tables, from 2 to 10.

Do ... While loopsdo ... while loop is almost identical to the while loop, except that the condition comes at the end:

dostatementwhile (condition)

The difference is that your statement gets executed at least once. In a normal while loop, the condition could be met before your statement gets executed.

The Break Statementwhen you need to break out of a loop before the whole thing gets executed. Or, you want to break out of the loop because of an error your user made. In which case, you can use the break statement.TeacherInterrupts = truecounter = 1while (counter < 11) {document.write(" counter = " + counter + "<BR>")if (TeacherInterrupts == true) breakcounter++}

Page 11: Javascript Conditional Statements

Try the code out and see what happens.

 The ‘Continue’ statementContinue will break the current loop and starts executing for next values.

Switch StatementsA switch statement is used when you want to choose just one of several possible outcomes.A better way to do the testing is with a switch statement. Here, the value in Age is coming from a drop-down combo box on a form called frmOne:Age = document.frmOne.cmbAge.valueswitch (Age) {case "1":alert("still at school")breakcase "2":alert("still young")breakcase "3":alert("start lying")breakcase "4":alert("start saving")breakdefault:alert("undetermined")}

The switch statement starts with the word switch. Each value that could be in your variable is preceded by the word case. A colon comes after the value. If the value is going to be text, then use double quotes; if the value is going to be a number, don't use the quotes:case "1":All we're saying is, "If it is the case that the variable Age holds the value "1", then we've found a winner."Once a match has been found, any code after the colon ( : ) will be executed. For us, that was an alert box:alert("still at school")

You have to tell JavaScript to break out of the switch statement. Just use the break statement, otherwise the next case down will get executed as well:

Page 12: Javascript Conditional Statements

case "1":alert("still at school")break

It was mentioned that the value in Age was coming from a drop-down box on a form. Here's the HTML code for that:<form name=frmOne><select name = cmbAge><option value = 1>5 to 16</option><option value = 2>17 to 30</option><option value = 3>31 to 45</option><option value = 4>46+</option></select></form>

We have four options in the drop down box, each with a value 1 to 4. It's this value that is going into the variable Age. Because the value from a HTML drop-down box will be a string (text) and not a number, each value for the case was surrounded by double quotes.Switch statements are an ideal way to check the value returned from a drop down box on a form. Instead of having an alert box in the case statement, you could direct your users to another web page. Like this:page = document.frmOne.cmbAge.valueswitch (page) {case "1":document.URL = "page1.html"breakcase "2":document.URL = "page2.html"breakcase "3":document.URL = "page3.html"breakcase "4":document.URL = "page4.html"breakdefault:alert("An error occurred, so we are staying here")}

The default is what you get when none of your case statements are true.

Page 13: Javascript Conditional Statements

Some more examples:

To print numbers in the fashion shown below:(a).

11 2 1 2 3 . . . ..    ..    ..    ..    .

Take ‘n’ value from user using textfield.

n = document.formname.textfield.value

    for(i=0 ; i<n ; i++)    {        for(j=1 ; j<=i ; j++)        document.write(j+"&nbsp;&nbsp;");        document.write("<br />");    }

(b)..    ..    ..    .    .    .1 2 3. . . .1 21

Take ‘n’ value from user using textfield.n = document.formname.textfield.value

    for(i=n ; i>0 ; i--)    {        for(j=1 ; j<i ; j++)        document.write(j+"&nbsp;&nbsp;");        document.write("<br />");

Page 14: Javascript Conditional Statements

    }

(c). We can also embed HTML tags inside the loop, as shown below.

var i=0for(i=1; i<=10 ;i++)document.writeln("<input type='text' value='"+i+"' />");        Above code will display 10 textboxes with value incrementing.

(d). Example for ‘break’

var i=0;for (i=0;i<=25;i++){if (i==7)  {  break;  }document.write("The number is " + i);document.write("<br />");

    Above code will print number from 0-6, when i=7, loop breaks.

(e). Example for ‘continue’

var i=0;for (i=0;i<=10;i++){if (i==7)  {  continue;  }document.write("The number is " + i);document.write("<br />");

    Above  code will break the current loop and continue with the next value when i=7. Therefore it will print upto 10.

Page 15: Javascript Conditional Statements

Java script

Arrays!An array is a variable that holds more than one number, or more than one string. Basically an array object is used to store multiple values in a single variable. Let's start explaining how arrays work.

Why Array?

If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:cars1 = "Saab";cars2 = "Volvo";cars3 = "BMW";However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?The best solution here is to use the concept of arrays!An array can hold all your variable values under a single name. And you can access the values by referring to the array name.Each element in the array has its own ID so that it can be easily accessed.(Above example reference: http://www.w3schools.com)

Setting up an Array:To set up an array in JavaScript you have to create an array object.Seasons = new Array(3)The above code would set up an array that could hold four different values in it (arrays start at zero). To put something into each "slot" in the array, you'd just do this:Seasons[0] = "Winter"Seasons[1] = "Spring"Seasons[2] = "Summer"Seasons[3] = "Autumn"

Our array is called Seasons. In between round brackets, we had an upper limit for the array - 3. (The number in square brackets is called the Index). When we're assigning values to each position in the array, we just type the name of the array, and then one of the numbers in square brackets. After typing the assignment operator (=), we type the value we want to go into that "slot" of the array.Another way to set up an array is to have all the values inside the round brackets of the word Array. Like this:Seasons = new Array("Winter", "Spring", "Summer", "Autumn")We still have an array with four values in it, but we've fixed the values inside of the round brackets.

Page 16: Javascript Conditional Statements

To get at the value inside an array, just use its index number. Like this:So putting that altogether in a script would give us this:

<SCRIPT language="javascript">Seasons = new Array(3)Seasons[0] = "Winter"Seasons[1] = "Spring"Seasons[2] = "Summer"Seasons[3] = "Autumn"alert(Seasons[2])</SCRIPT>

Test out the script in a web page and see how it works. Change the value of the index from 2 to one of the other numbers and see what happens. Change the value of the index to a number higher than 3 and see what happens.

Array Object Properties:constructor Returns the function that created the Array object's prototypelength Sets or returns the number of elements in an arrayprototype Allows you to add properties and methods to an object

Array Object Methods:concat() Joins two or more arrays, and returns a copy of the joined arraysjoin() Joins all elements of an array into a stringpop() Removes the last element of an array, and returns that elementpush() Adds new elements to the end of an array, and returns the new lengthreverse() Reverses the order of the elements in an arrayshift() Removes the first element of an array, and returns that elementslice() Selects a part of an array, and returns the new arraysort() Sorts the elements of an arraysplice() Adds/Removes elements from an arraytoString() Converts an array to a string, and returns the resultunshift() Adds new elements to the beginning of an array, and returns the new lengthvalueOf() Returns the primitive value of an array

For example:Seasons = new Array(3)Seasons[0] = "Winter"Seasons[1] = "Spring"Seasons[2] = "Summer"Seasons[3] = "Autumn"Seasons.sort()

Page 17: Javascript Conditional Statements

Seasons.join()alert(Seasons)

Arrays and Loops If you want to assign a value to a position in an array, you can just do this:Array[9] = "SiliconIndia Network"To display the value, just access its index number again:alert(Array[9])The fact that you can access the index number of an array to assign values makes them very handy in loops. To start our lottery number generator (UK lottery), we're going to create an array of 49 numbers. Number 1 will be at position 1 in the array, number 2 at position 2, etc. We could do this for all 49 numbers:Lottery = new Array(49)Lottery[1] = 1Lottery[2] = 2Lottery[3] = 3Lottery[4] = 4

But we'd have a laborious job typing all the array positions out, and all the values for them. Instead, we can use a loop to fill our array with the numbers 1 to 49. Here's the loop we can use:for (i = 1; i < 50; i++) {Lottery[i] = i}we assign the value of i to a position in our array:Lottery[i] = iTo demonstrate that it does indeed work, create this form on a new web page:<form name = frmOne><textarea name=taAll rows=10 cols=15></textarea><input type=button value=" Get Lottery Numbers" onClick=getNumbers() /></form>

Note: Good practice to write javascript is to write in ‘head’ section as a function and call anywhere in the ‘body’ section.

<SCRIPT language=JavaScript>function getNumbers() {TA = document.frmOne.taAlllottery = new Array(49)for (i = 1; i < 50; i++) {lottery[i] = iTA.value = TA.value + lottery[i] + " "}

Page 18: Javascript Conditional Statements

}</SCRIPT>

All that line is doing is adding the values in our array to the text area.When you click the button, the numbers 1 to 49 will be added to your text area.For a lottery, though, we need to shuffle all the numbers. Otherwise, everybody would win!

Shuffling the numbers in an ArrayOK, the next thing we want to do is shuffle our numbers up. Once the numbers are shuffled up, we can just peel off the first six for our lottery numbers. Again, we'll use arrays inside loops to do this for us.The code that shuffle the numbers up might be a tad complex at this stage of your programming career. The code is this:

for (i = 1; i < 50; i++) {newnumber = (Math.random() * 49) + 1newnumber = parseInt(newnumber, 10)temp = lottery[i]lottery[i] = lottery[newnumber]lottery[newnumber] = temp}

When you add it to your other code, your script should look like this (new code is in red bold text):

<SCRIPT Language = JavaScript>function getNumbers() {temp = 0newnumber = 0document.frmOne.taAll.value = ""TA = document.frmOne.taAlllottery = new Array(49)for (i = 1; i < 50; i++) {lottery[i] = i}for (i = 1; i < 50; i++) {newnumber = (Math.random() * 49) + 1newnumber = parseInt(newnumber, 10)temp = lottery[i]lottery[i] = lottery[newnumber]lottery[newnumber] = temp}}</SCRIPT>

Page 19: Javascript Conditional Statements

The first few new lines are just setting up variables temp and newnumber, and clearing the text area:temp = 0newnumber = 0document.frmOne.taAll.value = ""Notice, too, that the code that inserted numbers into the text area has now been cut. We'll use another for loop to display the shuffled numbers. So our first for loop is just this:for (i = 1; i < 50; i++) {lottery[i] = i}That's the for loop that puts the numbers 1 to 49 into our array. But they are in a nice orderly fashion. What we want is to shuffle them up a bit. Hence our rather complex second for loop:The idea behind our shuffle code is this: Grab a random number from 1 to 49. Store the current array value in a temp variable. Get the array[Random Number] value and put this into the current array value. Swap the current array value with the array[Random Number] value.That explanation might not be quite so crystal clear, but all the code is doing is swapping numbers around. The first two lines in the for loop get us our random number:newnumber = (Math.random() * 49) + 1newnumber = parseInt(newnumber, 10)The code Math.random() gets you a random number between 0 and 1. We're then multiplying that random number by 49, then adding 1. This will ensure that we get a random number between 1 and 49. Except, the number will be a floating point number. A rather long one. Something like this:12.34528569To chop off the part after the point, we can use the in-built function parseInt(). We need only pass it the number and what numerical base we want (10 will get you decimal).The rest of the code works like this (assuming the random number generated is 12)

temp = lottery[1]lottery[1] = lottery[12]lottery[12] = temp

In other words, the numbers 1 and 12 have swapped places. Don't worry if you don't understand what's going on. The rest of the code is a lot easier.OK, we've found a way to jumble up all our nice, orderly numbers. Now what?Well, we can use a loop to display the results of all that jumbling. Add this for loop underneath the code that shuffled the numbers:for (i = 1; i < 50; i++) {TA.value = TA.value + "lottery[" + i + "] = " + lottery[i] + " "}All the code inside that loop is doing is putting the array values into the text area. It's adding a bit of text along side the values as well. Try it out and see what happens. You should now see something like this in your text area (click the link to test out the programme so far):

Page 20: Javascript Conditional Statements

As you can see, our 49 numbers are nicely shuffled. All we need to do now is peel off the first six numbers and we have our very own lottery number generator. Which brings us neatly to an exercise.Using array methods like - ‘push()’ and ‘shift()’, we can implement ‘queue’ application.- ‘shift()’ and ‘unshift()’, we can implement ‘stack’ application and many more..

Multi-Dimensional arrays:Multi-dimensional arrays are not supported directly in JavaScript but you can construct them with arrays of arrays.An array can refer to another array with one of its elements. This means you can build multidimensional arrays, which are useful for working out 3D transformations.// Create a 2x2 array and store an identity matrix in it.var matrix = new Array(2);matrix[0] = new Array(2);matrix[1] = new Array(2);matrix[0][0] = 1;matrix[1][0] = 0;matrix[0][1] = 0;matrix[1][1] = 1;

Javascript Events and Functions

Page 21: Javascript Conditional Statements

JavaScript Events

JavaScript Events are items that transpire based on an action. A document event is the loading of an HTML document. A form event is the clicking on a button. Events are objects with properties.

Event Properties    x -Mouse x coordinate when the event happened.     y -Mouse y coordinate when the event happened. JavaScript defines five types of events which are form, image, image map, link, and window events. Events are associated with HTML tags. The definitions of the events described below are as follows: Form Events    blur - The input focus was lost.     change - An element lost the focus since it was changed.     focus - The input focus was obtained.     reset - The user reset the object, usually a form.     select - Some text is selected     submit - The user submitted an object, usually a form. Image Events    abort - A user action caused an abort.     error - An error occurred.     load - The object was loaded. Image Map Events    mouseOut - The mouse is moved from on top a link.     mouseOver - The mouse is moved over a link. Link Events    click - An object was clicked.     mouseOut - The mouse is moved from on top a link.     mouseOver - The mouse is moved over a link. Window Events    blur - The input focus was lost.     error - An error occurred.     focus - The input focus was obtained.     load - The object was loaded.     unload - The object was exited.

Event Association

Page 22: Javascript Conditional Statements

Events are associated with HTML tags. The definitions of the events described below are as follows:     abort - A user action caused an abort of an image or document load.     blur - A frame set, document, or form object such as a text field loses the focus for input.     click - Happens when a link or image map is clicked on     change - Happens when a form field is changed by the user and it loses the focus.     error - An error happened loading a image or document.     focus - A frame set, document, or form object such as a text field gets the focus for input.     load - The event happens when an image or HTML page has completed the load process in the browser.     mouseOut - The event happens when the mouse is moved from on top of a link or image map     mouseOver - The event happens when the mouse is placed on a link or image map.     reset - The user reset the object which is usually a form.     submit - The user submitted an object which is usually a form.     unload - The object such as a framesed or HTML document was exited by the user.

JavaScript Events - OnMouseDown

What we'll do is that follow is to detect the position of the mouse pointer when the user clicks on the screen. To do that, you need to find the X coordinate and the Y coordinate.

    * The X coordinate tells you how far left of the screen you are    * The Y coordinate tells you how far down the screen you are.

Both Netscape and Internet Explorer use the screenX and screenY property. If you're sure that your users will all have Internet Explorer, then the task is fairly easy. Here's the script:

<HEAD><TITLE>XY Coordinates</TITLE>

<SCRIPT Language = javascript>

function XYpos() {xPos = event.screenXyPos = event.screenYalert(xPos + " left " + yPos + " down")}

</Script>

Page 23: Javascript Conditional Statements

</HEAD>

<BODY onMouseDown = XYpos()>

 

The BODY section of the HTML is where we put the event handler onMouseDown. Now, every time the mouse is clicked anywhere in the Body of the web page, the function XYpos() gets called.

Inside the function, the property screenX and the property screenY (which are both properties of event) are put inside two variables:

xPos = event.screenXyPos = event.screenY

So xPos will hold how far left the mouse pointer is when the page is clicked; and yPos will hold far down the mouse pointer is when the page is clicked.

Both coordinates are then displayed in an alert box:

alert(xPos + " left " + yPos + " down")

If you have Netscape, however, the code will point blank refuse to work!

If we add our Browser detector code to the script above, though, we can get Netscape to display an error message. Try changing you code to this:

<Script language = javascript>Browser = navigator.appNameNet = Browser.indexOf("Netscape")Micro = Browser.indexOf("Microsoft")

Netscape = falseIE = false

if(Net >= 0) {Netscape = true}

if(Micro >= 0) {

Page 24: Javascript Conditional Statements

IE = true}

function XYpos() {if (IE == true) {xPos = event.screenXyPos = event.screenYalert(xPos + " left " + yPos + " down")}else if (Netscape == true) {alert("Script won't work: " + " " + "You're using Netscape")}}</script>

So Internet Explorer's way to get the coordinates of the mouse pointer is not too difficult. The reason why the script is so long is simply because Netscape refuses to cooperate. We therefore have to add browser detection code and do one thing for Internet Explorer and do another thing for Netscape.

 This below code works in both IE and FireFox/Mozilla. Try it, if you have both browsers:

function XYpos(event){alert(event.screenX + " left " + event.screenY + " down")}

<body onClick= XYpos(event) bgcolor = white>

onClick

We've already used this event quite a lot. But you can use it with buttons, images, links, radio buttons, check boxes. Here's a simple onClick event used with an image:

<IMG SRC = red.jpg onClick = "alert('No stealing the images!')">

onDblClick

Same as above, really. Try inserting Dbl into onClick and see what happens.

onKeyDown

Page 25: Javascript Conditional Statements

This events fires when a key on your keyboard is pressed. It applies to buttons, textboxes, text areas, and links. If you had a search box on a form, for example, you might want to activate the search when the user presses the Return/Enter key on the keyboard. For Netscape users, though, you need to use this:

window.captureEvents(Event.KEYPRESS)

And that's only the start of your problems!

An easier example of the KeyDown event that works in both browsers is this:

<INPUT type = text onKeyDown = "alert('Key pressed')">

onMouseOver

You've seen this in action already when we wrote the script for the "dancing hand". Associated events are onMouseOut and onMouseDown. They are mainly used for links and images. A typical use of onMouseOver is to swap images around when creating a rollover effect.

Onblur

This event takes places when objects lose focus. If you click inside one text box then click outside it the textbox has lost focus. That's when the onBlur event fires.

<INPUT TYPE = text onBlur = "alert('Lost focus')">

Here's an example. Click inside the first text box, then click inside the second one.

When you move away from the textbox, you should see the alert box. You can write code to check if something like an email address is correct. If not, you can reset the text box to a blank string.

onSubmit

This is a very useful event that can be used for data validation on a form. You can use this event with a Submit button. The details on the form can then be checked for errors. If you catch any errors, you can then stop the form's details from being submitted. Here's an example. Note the use of the word return. This is set to a Boolean value. If return is false then

Page 26: Javascript Conditional Statements

the form doesn't get submitted; if it's true then the form is submitted.

<FORM name = Si onSubmit = "return Validate()"><INPUT Type = Submit Value = " Send "></FORM>

The form is not much good because it only has a submit button. But notice where the onSubmit event is - in the FORM tag, and not with the Submit button.

Here's the Validate() function. It doesn't do any checking. All it does is to display an alert message.

function Validate() {

Details = falseif (Details == false) {alert("errors detected")return false}

if (Details == true) {alert("Form Submitted")return true}}

In the function, we've set a variable (Details) to false. This is just for testing purposes, and means the user has filled out the form incorrectly. Look at the two return values, though. If the Details are false then return gets set to false, and the form isn't submitted; if the Details are true then return is true, and the form is submitted.

Event HandlersEvent handlers are created as follows: onEvent = "Code to handle the event"The following example demonstrates its use: <a href="independent/index.html" target="_top" onMouseOver="window.status='To Independent Technologies Section' ;return true" onMouseOut="window.status='';return true"><img SRC="gifs/greenindependentbutton2.gif" ALT="Independent Technologies" VSPACE=3 BORDER=0 height=35 width=120></a><BR> As you can see, the event handling attribute is included in the HTML tag. When multiple statements are included in the event handling code, the statements are separated by a

Page 27: Javascript Conditional Statements

semicolon. The following example can be used to redirect a link to another location: <HTML><HEAD><TITLE>Using functions as event handlers</TITLE><SCRIPT LANGUAGE="JavaScript"><!--function nameDefined(ckie,nme){   var splitValues   var i   for (i=0;i<ckie.length;++i)   {      splitValues=ckie[i].split("=")      if (splitValues[0]==nme) return true   }   return false}function delBlanks(strng){   var result=""   var i   var chrn   for (i=0;i<strng.length;++i) {      chrn=strng.charAt(i)      if (chrn!=" ") result += chrn   }   return result}function getCookieValue(ckie,nme){   var splitValues   var i   for(i=0;i<ckie.length;++i) {      splitValues=ckie[i].split("=")      if(splitValues[0]==nme) return splitValues[1]   }   return ""}function testCookie(cname, cvalue) {  //Tests to see if the cookie    var cookie=document.cookie        //with the name and value

Page 28: Javascript Conditional Statements

   var chkdCookie=delBlanks(cookie)  //are on the client computer   var nvpair=chkdCookie.split(";")   if(nameDefined(nvpair,cname))  //See if the name is in any pair   {         tvalue=getCookieValue(nvpair,cname)  //Gets the value of the cookie      if (tvalue == cvalue) return true       else return false   }   else return false}function redirectLink() {   if (testCookie("javahere", "yes")) {      window.location="javahere.html"   }   else{      var futdate = new Date()      var expdate = futdate.getTime()      expdate += 3600*1000  //expires in 1 hour(milliseconds)      futdate.setTime(expdate)      var newCookie="javahere=yes; path=/;"      newCookie += " expires=" + futdate.toGMTString()      window.document.cookie=newCookie      window.location="javanot.html"   }}//--></SCRIPT></HEAD><BODY><H3>Using an event handler to direct a link based on a cookie value</H3><P><A NAME="Here" onClick="return redirectLink()">See if you've been here.</A></P></BODY></HTML>

JavaScript FunctionsDefining Functions

JavaScript functions are defined using the key word "function" followed by its name and variables being passed to it in the following syntax: function fname(value1,value2, ...)

Page 29: Javascript Conditional Statements

{   statement1   statement2   .}An example: <HTML><HEAD><TITLE>A function definition</TITLE><SCRIPT LANGUAGE="JavaScript"><!-- Hiding JavaScriptfunction listItems(itemList) {   document.write("<UL>\n")   for (i = 0;i < itemList.length;i++)   {      document.write("<LI>" + itemList[i] + "\n")   }   document.write("</UL>\n") } // End hiding JavaScript --></SCRIPT> </HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript"><!--days = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")listItems(days)// --> </SCRIPT> </BODY> </HTML>

Calling FunctionsIf evaluate() is a defined function, the following line will call the function: <SCRIPT LANGUAGE="JavaScript"><!--i3 = evaluate (Tree)// -->

Page 30: Javascript Conditional Statements

</SCRIPT>This function may evaluate the members of the array tree to see how many match a certain criteria. Another way to call a function is to tie it to an anchor: <A HREF="javascript:redirectLink()">redirecting</A>Another way is to tie it to an event: <A NAME="javatest" onClick="redirectLink()">redirecting</A>This will cause the redirectLink() function to run when the text "redirecting" is clicked on. The text inside the anchor reference is not marked as a link, nor does the mouse change when placed over the text. This is one way to make truly invisible links, that no one would know had any function until they click on it. Functions PropertiesFunctions in JavaScript is actually an object. Therefore any created function created using the "function" declaration will have the properties of a function. These properties are: •    arguments - An array of arguments passed to the function. This is an array object which has a property of length which enables the programmer to tell how many arguments (or variables)are passed to the function. •    caller - The name of the function that called the function. •    prototype - Used to make more properties. Using the Arguments ArrayThe arguments array is a member of every function. It can be used to determine how many variables are being passed to the function, and what they are, without each argument being explicitly declared in the function. The following example performs the same task as the above example: function listItems() {   var items = listItems.arguments.length   document.write("<UL>\n")   for (i = 0;i < items;i++)   {      document.write("<LI>" + listItems.arguments[i] + "\n")   }   document.write("</UL>\n") } The function may be called as follows: listItems("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Happyday")Local variablesLocal variables may be defined inside functions. The following example uses the variables, sum and items as local variables. function average()

Page 31: Javascript Conditional Statements

{   var items = average.arguments.length   var sum = 0   for (i = 0; i < items;i++)   {      sum += average.arguments[i]   }   return (sum/items)}document.write(average(6,9,8,4,5,7,8,10))ReturnAs in the example above, the return statement will return a value to the statement that invoked the function. In the above example, the average value is written to the document. The return statement will return the value as float, string, integer or whatever is appropriate for use. Lets discuss JavaScript predefined functions such as escape, unescape, eval, isNaN, tostring, alert, and othersConversion and Comparison    escape(string) - Encodes a string from ASCII into an ISO Latin-1 (ISO 8859-1) character set which is suitable for HTML processing. It is passed the string to be encoded, and returns the encoded string.     unescape - Converts an ISO8859-1 character set to ASCII. If a string is "My phone # is 123-456-7890", after the escape function, it is "My%20phone%20%23%20is%20123-456-7890". After unescape, it is "My phone # is 123-456-7890".     eval()- Converts a string to integer or float value. It can also evaluate expressions included with a string. In the example, value1 becomes 62. value1 = eval("124/2") ,     isNaN(value) - If the value passed is a not a number, the boolean value of true is returned, if it is a number, it returns false.     if (isNaN(string1))    {       document.write("String1 is not a number\n");    }    else    {       document.write(String1 is a number\n");    }    parseFloat() - Returns floating point numbers the same as the parseInt function, but looks for floating point qualified strings and returns their value as a float. The first line below returns a value of 123, and the second line returns 9.683.     value1 = parseFloat("123")    value2 = parseFloat("9.683")

Page 32: Javascript Conditional Statements

    parseInt()- Converts a string to an integer returning the first integer encountered which is contained in the string. In the example, value1 becomes 12. value1 = parseInt("12b13") , If no integer value were found such as in the string "abcd", then a value of 0 is returned.     typeof operator - This is an operator but its usefullness is similar to a function. This operator returns the type of the object it operates on. Values returned are string values and may be one of "undefined", "object", "function", "number", "Boolean", or "string". The example will return the string "number". typeof 10     taint     untaint(element) -     valueOf()

Methods that belong to all objects    toString() - Converts an object to a string. The syntax is shown below. Radix is the base value for the conversion, which may be 10 for decimal conversion. The value 1 is used for binary conversion, and 8 is used for octal conversion. object.tostring(radix) Dialog Boxes    alert(message) - Displays an alert box with a message defined by the string message. Example: alert("An error occurred!")     confirm(message) - When called, it will display the message and two boxes. One box is "OK" and the other is "Cancel". If OK is selected, a value of true is returned, otherwise a value of false is returned. An example:     if (confirm("Select OK to continue, Cancel to abort"))    {       document.write("Continuing")    }    else    {       document.write("Operation Canceled")    }    prompt(message) - Displays a box with the message passed to the function displayed. The user can then enter text in the prompt field, and choose OK or Cancel. If the user chooses Cancel, a NULL value is returned. If the user chooses OK, the string value entered in the field is returned. An example:     var response=prompt("Enter your name")    if (response != null)    {       document.write(response)

Page 33: Javascript Conditional Statements

    }

Calling other functions within a function

Functions can call other functions, and have a value passed back to the calling line. We'll see how that works now. Once you have grasped the concept, what we're then going to do is write code to validate data that a user might enter on a form.

First, though, here's an example of a function being called inside another function. To test it out, create a web page with a button on it. Set the onClick event for the button to this:

onClick = GetValue()

Once you have your web page with a button on it, add this code to the HEAD section of the page:

<Script language = JavaScript>

function GetValue() {

return value()}

function returnvalue() {

n1 = 10n2 = 5answer = n1 - n2return false}

</SCRIPT>

When the button on your page is clicked, it calls the function GetValue(). The only line of code in the GetValue() function calls the second function:

returnvalue()

When this second function is called, all the code inside it is executed. Control then passes back to the first function. Any other lines for the first function are then executed.

Page 34: Javascript Conditional Statements

Notice the line of code that reads return false. We really should have had this return word at the end of all our functions. It's actually a question: "Does the function return a value?" In other words, Are we finished with this function or not?

If the function does return a value you can either use return true, or more likely you can return a value back to the first function. In our second function, we were subtracting one number from another and putting the answer into a variable called answer. But we weren't doing anything with this variable, so nobody would be able to see what the answer was. In this next example, we'll return the answer to the first function:

function GetValue() {

total = returnvalue()alert(total)}

function returnvalue() {

n1 = 10n2 = 5answer = n1 - n2return answer}

The first function now does something slightly different. The call to the second function, returnvalue(), has gone on the right hand side of an equals sign (= ). On the left hand side of the equals sign we have a variable called total. What we're saying here is "Assign the value of returnvalue() to the total variable."

But the same thing happens: the second function is called and has its code executed. However, we've now told the second function to return a value:

return answer

And what's inside the answer variable? The answer to the sum 10 - 5. This is the value that gets passed back to the calling line, which was:

total = returnvalue()

Now the variable total will hold the value from the function. Finally, we've displayed the result

Page 35: Javascript Conditional Statements

in an alert box. Run the code and see how it works.

Java script

JavaScript Form Validation

The form you'll work with is quite simple. It will be used only for your visitors to leave their name, email address and some comments. They will be invited to say what they liked about the site, and what they didn't like. This will be done with check boxes. The form we're going to use can be copied to your own computer by clicking the link below. When the web page loads, save a copy to your hard drive. So load it up and let's do some coding.

When the Submit button on the form is clicked, we'll use functions to validate the form. If we detect anything not quite right, we'll invite the user to try again. If the form is OK, we'll send it to an email address.

validateFormOnSubmit ( )

This is a main function that calls a series of subfunctions, each of which checks a single form element for compliance. If the element complies than sufunction returns an empty string. Otherwise it returns a message describing the error and highlight appropriate element with yellow.

function validateFormOnSubmit(theForm) {var reason = "";

  reason += validateUsername(theForm.username);  reason += validatePassword(theForm.pwd);  reason += validateEmail(theForm.email);  reason += validatePhone(theForm.phone);  reason += validateEmpty(theForm.from);        if (reason != "") {    alert("Some fields need correction:\n" + reason);    return false;  }

  return true;}

validateEmpty ( )

Page 36: Javascript Conditional Statements

The function below checks if a required field has been left empty. If the required field is blank, we return the error string to the main function. If it’s not blank, the function returns an empty string.

function validateEmpty(fld) {    var error = "";     if (fld.value.length == 0) {        fld.style.background = 'Yellow';         error = "The required field has not been filled in.\n"    } else {        fld.style.background = 'White';    }    return error;  }

validateUsername ( )

The function below checks if the user entered anything at all in the username field. If it’s not blank, we check the length of the string and permit only usernames that are between 5 and 15 characters. Next, we use the JavaScript regular expression /\W/ to forbid illegal characters from appearing in usernames. We want to allow only letters, numbers and underscopes

function validateUsername(fld) {    var error = "";    var illegalChars = /\W/; // allow letters, numbers, and underscores     if (fld.value == "") {        fld.style.background = 'Yellow';         error = "You didn't enter a username.\n";    } else if ((fld.value.length < 5) || (fld.value.length > 15)) {        fld.style.background = 'Yellow';         error = "The username is the wrong length.\n";    } else if (illegalChars.test(fld.value)) {        fld.style.background = 'Yellow';         error = "The username contains illegal characters.\n";    } else {        fld.style.background = 'White';    }    return error;}

validatePassword ( )

Page 37: Javascript Conditional Statements

The function below checks the password field for blankness and allow only letters and numbers - no underscopes this time. So we should use a new regular expression to forbid underscopes. This one /[\W_]/ allow only letters and numbers. Next, we want to permit only passwords that contain letters and at least one numeral. For that we use the seacrh() method and two more regular expressions: /(a-z)+/ and /(0-9)/.

function validatePassword(fld) {    var error = "";    var illegalChars = /[\W_]/; // allow only letters and numbers      if (fld.value == "") {        fld.style.background = 'Yellow';        error = "You didn't enter a password.\n";    } else if ((fld.value.length < 7) || (fld.value.length > 15)) {        error = "The password is the wrong length. \n";        fld.style.background = 'Yellow';    } else if (illegalChars.test(fld.value)) {        error = "The password contains illegal characters.\n";        fld.style.background = 'Yellow';    } else if (!((fld.value.search(/(a-z)+/)) && (fld.value.search(/(0-9)+/)))) {        error = "The password must contain at least one numeral.\n";        fld.style.background = 'Yellow';    } else {        fld.style.background = 'White';    }   return error;}

validateEmail ( )

Next we want to see if the email address the user entered is real. This means that the input data must contain at least an @ sign and a dot (.). Also, the @ must not be the first character of the email address, and the last dot must at least be one character after the @ sign.

At first we check if the user entered anything at all in the email field. Next, we use regular expression and the test() method to check the field for a compliance. Also we will use trim() function that will trim leading whitespace off the string. This won’t be perfect validation — it is possible to slip not compliant addresses by it — but it's normally good enough.

function trim(s){  return s.replace(/^\s+|\s+$/, '');}

function validateEmail(fld) {    var error="";

Page 38: Javascript Conditional Statements

    var tfld = trim(fld.value);                        // value of field with whitespace trimmed off    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;       if (fld.value == "") {        fld.style.background = 'Yellow';        error = "You didn't enter an email address.\n";    } else if (!emailFilter.test(tfld)) {              //test email for illegal characters        fld.style.background = 'Yellow';        error = "Please enter a valid email address.\n";    } else if (fld.value.match(illegalChars)) {        fld.style.background = 'Yellow';        error = "The email address contains illegal characters.\n";    } else {        fld.style.background = 'White';    }    return error;}

function trim(s){  return s.replace(/^\s+|\s+$/, '');}

function validateEmail(fld) {    var error="";    var tfld = trim(fld.value);                        // value of field with whitespace trimmed off    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;       if (fld.value == "") {        fld.style.background = 'Yellow';        error = "You didn't enter an email address.\n";    } else if (!emailFilter.test(tfld)) {              //test email for illegal characters        fld.style.background = 'Yellow';        error = "Please enter a valid email address.\n";    } else if (fld.value.match(illegalChars)) {        fld.style.background = 'Yellow';        error = "The email address contains illegal characters.\n";    } else {        fld.style.background = 'White';    }    return error;}

Page 39: Javascript Conditional Statements

validatePhone ( )

The function below checks if the phone number is valid. At first we use regular expression and the replace() method to clear out any spacer characters. Next, we use the isNaN() function to check if the phone number contain only numbers. At last we check the length of the string and permit only phone numbers with 10 digits.

function validatePhone(fld) {    var error = "";    var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');   

   if (fld.value == "") {        error = "You didn't enter a phone number.\n";        fld.style.background = 'Yellow';    } else if (isNaN(parseInt(stripped))) {        error = "The phone number contains illegal characters.\n";        fld.style.background = 'Yellow';    } else if (!(stripped.length == 10)) {        error = "The phone number is the wrong length. Make sure you included an area code.\n";        fld.style.background = 'Yellow';    }    return error;}

HTML Form

This script accompanies an HTML form. When the user clicks the Submit button on the form, the form data is sent to a JavaScript validation function that checks each field to make sure that it is in the appropriate format. The HTML form could look something like this:

<html><head><title>WebCheatSheet - JavaScript Tutorial</title></head><body><h1>WebCheatSheet - JavaScript Tutorial</h1>

<form name="demo" onsubmit="return validateFormOnSubmit(this)" action="test.htm"><table summary="Demonstration form">  <tbody>  <tr>    <td><label for="username">Your user name:</label></td>    <td><input name="username" size="35" maxlength="50" type="text"></td>  </tr>  

Page 40: Javascript Conditional Statements

  <tr>    <td><label for="pwd">Your password</label></td>    <td><input name="pwd" size="35" maxlength="25" type="password"></td>  </tr>     <tr>    <td><label for="email">Your email:</label></td>    <td><input name="email" size="35" maxlength="30" type="text"></td>  </tr>    <tr>    <td><label for="phone">Your telephone number:</label></td>    <td><input name="phone" size="35" maxlength="25" type="text"></td>  </tr>     <tr>    <td>        <label for="from">Where are you :</label></td>    <td><input name="from" size="35" maxlength="50" type="text"></td>  </tr>     <tr>    <td>&nbsp;</td>    <td><input name="Submit" value="Send" type="submit" ></td>    <td>&nbsp;</td>  </tr>  </tbody></table></form>

</body></html>

The first thing to do is to set up a function to handle the onSubmitevent. This function will call other functions: one function to checkthe Name text box, one to check the email address, and so on. So openup the code for the form. Notice the names of our form elements:

Form Name:f1 Name textbox:Name Email textbox:Email Comments text area:Comments Likes Checkboxes:Liked Dislikes Checkboxes:Hated

Page 41: Javascript Conditional Statements

Submit Button Event: Validate()

And here's the function for the Submit event:

function Validate() {

Message = ""Message = Message + CheckName()Message = Message + CheckEmail()Message = Message + CheckComments()Message = Message + CheckLikes()Message = Message + CheckHates()

if (Message == "") {return true}else {alert(Message)return false}}

All we're going to be doing is building up a variable called Message. At the start, Message is set to a blank string:

Message = ""

If, after all our functions have been called, Message is still a blank string, then no errors have occurred. If no errors have occurred, we can set return to true. Setting return to true will ensure that the form gets sent. If an error has occurred, then a function will insert some text into the Message variable. If Message contains any text, then return gets set to false. When return is false the form doesn't get sent, and the message itself will be displayed in an alert box:

if (Message == "") {return true}else {alert(Message)return false}

Look at the lines that call the functions, though. Here's the first one, the function that checks the Name textbox:

Page 42: Javascript Conditional Statements

Message = Message + CheckName()

So we're saying "Put into the variable Message the value returned from the function CheckName(). Keep what was originally in the variable Message." Here's the function to add to your code:

CheckName() {UserName = document.f1.Name.value

if (UserName == "") {Message = "Something's wrong with your name" + " "}else {Message = ""}return Message}

First, we put the value from the Name textbox into a variable called UserName:

UserName = document.f1.Name.value

Then we have an if statement to check what is inside of UserName. If the textbox is blank then the user hasn't entered a name, and the variable UserName will be a blank string. In which case it's an error. If there is something in the textbox then no error has occurred and we can set the Message variable to a blank string.

if (UserName == "") {Message = "Something's wrong with your name" + " "}else {Message = ""}

Finally, we tell the function to return whatever is inside the Message variable:

return Message

So after the first function call we'd really have either this:

Message = "Something's wrong with your name" + " "

Or this:

Message = ""

Page 43: Javascript Conditional Statements

If it's the first one, the form won't get sent; if it's the second one, then the user filled the name in correctly.

In the next part, we'll continue with the functions on our form. We'll tackle email addresses next.

Form Validation

Any sort of interactive site is going to have form inputs — a place where your users input who they are, what they want to buy, where they live, and so forth. This data is passed to whatever handles your back end — a Perl CGI script, a PHP engine, a database like Oracle, or some other technology you’ve invested in. Whatever system is back there, you can bet that it doesn’t appreciate having its time wasted with bogus information, and chances are the user doesn’t appreciate it either. If the data the user submits to the CGI contains an error, there will be a noticeable lag — typically several seconds — before the information travels over the Internet to the server, is examined on the server, and then returns to the user along with an irritating error message.

If you run a little preliminary validation of the user’s form input before the form is submitted, there will be no wait time. Client-side validation is instantaneous because it doesn’t have to transmit any data. JavaScript catches any erroneous data the user enters before it goes anywhere.

Double-checking the data on the server remains necessary, in case the user has turned JavaScript off or somehow finds a way to circumvent the client-side validation, either maliciously or by accident. For the majority of your users, JavaScript form validation will save a lot of time up front.The Script’s Purpose

This script accompanies an HTML form. When the user clicks the Submit button on the form, the form data is sent to a JavaScript validation function that checks each aspect of the input to make sure that it is in the appropriate format. Each form element is evaluated according to specified criteria. If the script finds an error in one of the fields, it sends back a warning explaining how the string doesn’t conform. The fairly robust string-handling and regular-expression techniques available in JavaScript handle this checking process.checkWholeForm()

A master function, called checkWholeForm() is placed at the top of the page that contains a form.

function checkWholeForm(theForm) {    var why = "";    why += checkEmail(theForm.email.value);    why += checkPhone(theForm.phone.value);    why += checkPassword(theForm.password.value);    why += checkUsername(theForm.username.value);    why += isEmpty(theForm.notempty.value);    why += isDifferent(theForm.different.value);

Page 44: Javascript Conditional Statements

    for (i=0, n=theForm.radios.length; i<n; i++) {        if (theForm.radios[i].checked) {            var checkvalue = theForm.radios[i].value;            break;        }     }    why += checkRadio(checkvalue);    why += checkDropdown(theForm.choose.selectedIndex);    if (why != "") {       alert(why);       return false;    }return true;}

This function calls a series of subfunctions, each of which checks a single form element for compliance with a specific string format and returns a message describing the error. If the function returns an empty string, we know the element complies.checkUsername()

Here’s the routine that checks to see if the user entered anything at all in the username field. (We’ll use the same routine to check each form field for blankness.)

function checkUsername (strng) { var error = ""; if (strng == "") {    error = "You didn't enter a username.\n"; }

We pass the value of the username field to this function, which compares that value to an empty string (""). If the two are the same, we know that the username field is blank, so we return the warning string to our master function. If it’s not blank, we move along to the next hurdle. We want to permit only usernames that are between 4 and 10 characters. We check the length of the string, and reject it if it’s too short or too long.

if ((strng.length < 4) || (strng.length > 10)) {    error = "The username is the wrong length.\n";}

Next, we want to forbid certain characters from appearing in usernames. Specifically, we want to allow only letters, numbers, and underscores. We can test for that using regular expressions and the test() method. The regular expression functions found in JavaScript 1.2 are similar to Perl’s regular expressions, with a bit of simplification when it comes to syntax. If you know Perl, you should have no trouble wielding JavaScript’s regular expressions. The JavaScript regular expression /\W/ is a standard character class that’s handily predefined to mean "any character other than letters, numbers, and underscores." So we set the variable illegalChars equal to that

Page 45: Javascript Conditional Statements

regular expression, and then test the username string against that variable to see if a match is found. If it is, we throw up a warning.

var illegalChars = /\W/;  // allow only letters, numbers, and underscores    if (illegalChars.test(strng)) {       error = "The username contains illegal characters.\n";    }

By now, we’ve run the username through three tests. If it’s passed all three, it’s OK by us. We give the username a passing grade and move along to the next field.checkPassword()

For the password field, we want to constrain the length again (this time, we’ll keep it between 6 and 8 characters), and we want to allow only letters and numbers — no underscores this time. So we have to use a new regular expression to define which characters we’re banning. This one, like the last one, includes \W — everything but letters, numbers, and underscores — but we also need to explicitly mention underscores, so as to permit only letters and numbers. Hence: /[\W_]/.

function checkPassword (strng) { var error = ""; if (strng == "") {    error = "You didn't enter a password.\n"; }    var illegalChars = /[\W_]/; // allow only letters and numbers    if ((strng.length < 6) || (strng.length > 8)) {       error = "The password is the wrong length.\n";    }    else if (illegalChars.test(strng)) {      error = "The password contains illegal characters.\n";    }

When it comes to passwords, we want to be strict with our users. It’s for their own good; we don’t want them choosing a password that’s easy for intruders to guess, like a dictionary word or their kid’s birthday. So we want to insist that every password contain a mix of uppercase and lowercase letters and at least one numeral. We specify that with three regular expressions, a-z, A-Z, and 0-9, each followed by the + quantifier, which means “one or more,” and we use the search() method to make sure they’re all there:

else if (!((strng.search(/[a-z]+/) > -1)  && (strng.search(/[A-Z]+/) > -1)  && (strng.search(/[0-9]+/) > -1))) {  error = "The password must contain at least one     uppercase letter, one lowercase letter,    and one numeral.\n";  }

Page 46: Javascript Conditional Statements

checkEmail()

Next we want to see if the email address the user entered is real. The most effective way to do this is to go out on the Net and ask the domain the user claims to hail from if that the person actually has an account. But this takes a big toll on the machine that’s running the checks — and it isn’t possible with JavaScript anyway. With JavaScript we can check to see if the email string looks like an email address. We want it to follow this format: some characters, then an at symbol (@), then some more characters, then a dot (.), then two or three more characters, and that’s it. This won’t be perfect validation —it is possible to slip phony non-RFC-compliant addresses by it — but it’s normally good enough. If the pattern doesn’t match, we reject the email address.

The regular expression that expresses the format goes something like this: /^.+@.+\..{2,3}$/. The carat (^) means the start of the string and the dollar sign ($) means the end of the string. By surrounding the rest of the regular expression with these characters, we ensure that we evaluate the entire string, rather than just a portion. Each .+ means "at least one character" — the dot (.) means "any character"” and the plus sign (+), you recall, means "one or more." The .{2,3} portion means "two or three characters." And when we want to match a literal dot, we need to escape the character with a backslash. That’s why we have \. there.

var emailFilter=/^.+@.+\..{2,3,4,6}$/;if (!(emailFilter.test(strng))) {        error = "Please enter a valid email address.\n";}

Again, we want to check to make sure that no forbidden characters have slipped in. For email addresses, we’re forbidding the following: ( ) < > [ ] , ; : \ / "

var illegalChars= /[\(\)\<\>\,\;\:\\\/\"\[\]]/if (strng.match(illegalChars)) {   error = "The email address contains illegal characters.\n";

}

checkPhone()

To validate a phone number, first we want to clear out any spacer characters, such as parentheses, dashes, spaces, and dots. We can do this with a regular expression and the replace() method, replacing anything that matches our regular expression with a null string. Having done that, we look at what we have left with the isNaN() function (which checks to see if a given input is Not A Number), to test if it's an integer or not. If it contains anything other than digits, we reject it.

var stripped = strng.replace(/[\(\)\.\-\ ]/g, '');//strip out acceptable non-numeric charactersif (isNaN(parseInt(stripped))) {

Page 47: Javascript Conditional Statements

   error = "The phone number contains illegal characters.";}

Then we count the length of the number. It should have exactly ten digits — any more or less, and we reject it.

if (!(stripped.length == 10)) {    error = "The phone number is the wrong length.      Make sure you included an area code.\n";}

isDifferent()

We want to do a few more kinds of validation. If you present a license or something similar in a text box for the user to accept, you want to make sure that it hasn’t been altered when the form is submitted. That’s done very simply by comparing the submitted string with the string you were expecting.

function isDifferent(strng) {  var error = "";  if (strng != "Can\'t touch this!") {     error = "You altered the inviolate text area.\n";  }

Alternately, you can use the onChange() method to catch the user in the act of modifying the text and stop them before they submit the form.checkRadio()

To make sure that a radio button has been chosen from a selection, we run through the array of radio buttons and count the number that have been checked. Rather than sending the whole radio object to a subfunction, which can be problematic (because the radio object has no property indicating which value has been chosen), we pre-process the radio form element in a for loop and send that result to a subfunction for evaluation.

for (i=0, n=theForm.radios.length; i<n; i++) {   if (theForm.radios[i].checked) {      var checkvalue = theForm.radios[i].value;      break;   }}why += checkRadio(checkvalue); function checkRadio(checkvalue) {var error = "";   if (!(checkvalue)) {       error = "Please check a radio button.\n";

Page 48: Javascript Conditional Statements

    }return error;    }

check Dropdown()

Finally, we want to make sure that the user has selected an option from our drop-down menu (and not the first option, which isn’t an option at all, but just a "Choose one" header). For this, we use the select object’s selectedIndex property, which returns the index of the selected option. If the index is 0, we reject the input.

function checkDropdown(choice) {    var error = "";    if (choice == 0) {       error = "You didn't choose an option         from the drop-down list.\n";    }    return error;}   

JavaScript and Checkboxes

The only thing we're going to do with our check boxes on our form is to see if they have been ticked or not. If a box has been ticked, then no errors have occurred; if none of the boxes have been ticked, then an error has occurred, and the user will get an alert box. So our check box validation is a "yes" or "no" affair: Have they ticked a box or not?

What we're not doing is returned the text from the check boxes. The text for our check boxes was "Cool layout", "Easy to Navigate", etc. We're not passing these values back when the Submit button is clicked. All the same, we'll see how this is done.

On our Form, the Check box HTML code was this:

<input type="checkbox" name="Liked" value="Cool Layout">Cool Layout

<input type="checkbox" name="Liked" value="Easy to Navigate"> Easy to Navigate

<input type="checkbox" name="Liked" value="Great Contents">

The NAME value is crucial. For all our check boxes, the NAME is the same - "Liked". The text that people see on the page comes after the right angle bracket ( > ). The VALUE of the checkbox is the same as the text that people see on the page. (But it doesn't have to be).

With this in mind, here's our Check Box function:

function CheckLikes() {

Page 49: Javascript Conditional Statements

boxes = document.f1.Liked.lengthtxt = ""for (i = 0; i < boxes; i++) {if (document.f1.Liked[i].checked) {txt = txt + document.f1.Liked[i].value + " "} }

if (txt == "") {Message = "No Boxes ticked"}else {Message = ""}

return Message}

We start the function by getting the length of the check boxes:

boxes = document.f1.Liked.length

The length here means "How many Check Boxes are there". So our code reads "Of all the check boxes in the form called f1, how many are there with the name Liked?" The answer will be inserted into a variable called boxes.

After we set a variable called txt to a blank string (txt = "") we add a for loop to check all of the boxes with the NAME Liked:

for (i = 0; i < boxes; i++) {if (document.f1.Liked[i].checked) {txt = txt + document.f1.Liked[i].value + " "}}

Because we've given all of our checkboxes the same NAME, the browser can see them as an array of checkboxes. With an array, we can loop round checking values.

The for loop is set to start at zero, and the end condition is that value we put into the variable boxes - the number of checkboxes on our form.

Inside the loop, we can access the index number of each check box:

if (document.f1.Liked[i].checked)

Page 50: Javascript Conditional Statements

Because the for loop started at zero, the check box Liked[0] will be examined first. If it has been checked, a true value is returned. The statement below is then executed:

txt = txt + document.f1.Liked[i].value + " "

The VALUE from the check box Liked[0] is added to the variable called txt

Next time round the loop, the variable i will be 1. So the second check box will be examined to see if it was checked or not. If it has been, the VALUE of the checkbox is added to the txt variable.

And we go round and around examining the checkboxes called Liked. At the end of the loop, the variable txt will either hold the values from the check boxes, or it will still be a blank string. Depending on which it is, we can return a value for our function:

if (txt == "") {Message = "No Boxes ticked"}else {Message = ""}

return Message

Again, we're building up our Message variable. Or not building it up, if no boxes have been ticked.

The function for our second lot of check boxes, the ones called "Hated", works in exactly the same way as the function above. Except you would changed the "Liked" to "Hated".

And that concludes our script to check form elements for errors. Once you add all the code, and test it out, you'd get a message box when the form is submitted but nothing has been entered. Try out the code by clicking the link below. Leave everything blank, then click submit.

Click here to see the Form with all the code added

To see all the code, click View > Source (in Internet Explorer).

In the next few parts, we'll take a look at how to validate other form elements: drop down boxes, list boxes, and Radio Buttons.

Using JavaScript to Validate a Drop Down Box

A drop down box on a form allows you to select one option among many. It looks like this:

Page 51: Javascript Conditional Statements

Here's the HTML code for the above drop down box:

<SELECT NAME = s1><OPTION VALUE = "NE" selected >North East</OPTION><OPTION VALUE = "NW">North West</OPTION><OPTION VALUE = "SE">South East</OPTION><OPTION VALUE = "SW">South West</OPTION><OPTION VALUE = "Midlands">Midlands</OPTION></SELECT>

Notice the NAME of our Select box (as the drop down box is called in HTML world). The NAME we've chosen is s1. The name of our form is f1. So here's a function that gets which item the user selected:

function GetSelectedItem() { len = document.f1.s1.length i = 0 chosen = "none" for (i = 0; i < len; i++) { if (document.f1.s1[i].selected) { chosen = document.f1.s1[i].value } }

return chosen }

The code is similar to the check box code. We set the length of the select box (length is how many items in the list, minus 1 item):

len = document.f1.s1.length

Then inside the loop, we again access the index number of the SELECT object:

document.f1.s1[i].selected

So, s1[0] is the first item in the list, s1[1] the second item, s1[2] the third, and so on.

Page 52: Javascript Conditional Statements

Once the selected item has been detected, you access it's value property and pop it into a variable:

chosen = document.f1.s1[i].value

You can test out the script by selecting an item from the box below.

Top of Form

Bottom of Form

What we've done with this box is to add an event to the select box. The event calls the function:

<SELECT NAME = s1 onChange = GetSelectedItem()>>

In the next part, we'll see how to get at which items have been selected in a list box.

Using JavaScript to Validate a List Box

A form element closely related to the Select element is the Multiple select. This time, the elements is a list box where you can select more than one item. You select more than one item by holding down the Ctrl key on your keyboard and then clicking items with your left mouse button. Here's what they look like:

To get which items have been selected, we can use the same code we used for the drop down list. The only difference is the line inside the if statement:

Page 53: Javascript Conditional Statements

function GetSelectedItem() {

> len = document.f1.s1.lengthi = 0chosen = ""

for (i = 0; i < len; i++) {if (document.f1.s1[i].selected) {chosen = chosen + document.f1.s1[i].value + " "} }

}