You are on page 1of 23

Javascript is a scripting language that will allow you to add real programming to your webpages.

You can create small application type processes with javascript, like a calculator or a primitive game of some sort. However, there are more serious uses for javascript:

Browser Detection Detecting the browser used by a visitor at your page. Depending on the browser, another page specifically designed for that browser can then be loaded. Cookies Storing information on the visitor's computer, then retrieving this information automatically next time the user visits your page. This technique is called "cookies". Control Browsers Opening pages in customized windows, where you specify if the browser's buttons, menu line, status line or whatever should be present. Validate Forms Validating inputs to fields before submitting a form. An example would be validating the entered email address to see if it has an @ in it, since if not, it's not a valid address. Since javascript isn't HTML, you will need to let the browser know in advance when you enter javascript to an HTML page. This is done using the <script> tag. The browser will use the <script> type="text/javascript"> and </script> to tell where javascript starts and ends. Consider this example: <html> <head> <title>My Javascript Page</title> </head> <body> <script type="text/javascript"> alert("Welcome to my world!!!"); </script> </body> </html> The word alert is a standard javascript command that will cause an alert box to pop up on the screen. The visitor will need to click the "OK" button in the alert box to proceed. By entering the alert command between the <script type="text/javascript"> and </script> tags, the browser will recognize it as a javascript command. If we had not entered the <script> tags, the browser would simply recognize it as pure text, and just write it on the screen. You can enter javascript in both the <head> and <body> sections of the document. In general however, it is advisable to keep as much as possible in the <head> section.

THE FIRST SCRIPT

Knowing that javascript needs to be entered between <script> tags, is a start. But there are a few other things you need to know before writing your first javascript: Javascript lines end with a semicolon. You may have noticed from the example on the previous page that javascript lines end with a semicolon. You can easily put all your javascript on a single line without destroying the performance of it. However, you would destroy the overview of your script so it is not advisable. Always put the text within " ". When entering text to be handled by javascript, you should always put the text within " ". If you forget to enclose your text in " ", javascript will interpret your text as being variables rather than text. In the next section you will learn why this would cause an error to your script.

Capital letters are different from lowercase letters. You should always remember that capital letters are different from lowercase letters. This means that when you write commands in javascript, you need to type capital letters in the correct places, and nowhere else. Incorrect capitalization is probably the most common source of error for javascript programmers on all levels!!

Now consider this example: Instead of having javascript write something in a popup box we could have it write directly into the document. <html> <head> <title>My Javascript Page</title> </head> <body> <script> document.write("Welcome to my world!!!"); </script> </body> </html>

The document.write is a javascript command telling the browser that what follows within the parentheses is to be written into the document. Note: When entering text in javascript you need to include it in " ". The script in the example would produce this output on your page: Welcome to my world!!!

Consider this example to learn where javascript writes the text: <html> <head>

</head> <body> Hello!!!<br> CAPITAL LETTERS <script> document.write("Welcome to my world!!!<br>"); </script> Enjoy your stay...<br> </body> </html> It is extremely important to be aware that javascript makes a sharp distinction between capital and lowercase letters. The output from this example would look like this: Javascript does not consider a variable named myvalue to be the same as a variable named MYVALUE. Consider these examples: Hello!!! Welcome to my world!!! Example 1 stay... Example 2 Enjoy your <html> <html> <head> <head> Page</title> <title>My Page</title> As you <title>My can see, javascript simply writes the text to where the script is placed within the HTML codes. </head> </head> An interesting aspect is that you can write all kinds of HTML tags to webpages with the document.write <body> <body> method. <script> <script>Fahrenheit and Celsius, instead of actually For instance, if you wanted to make a long table that compared myvalue=2; myvalue=2; typing all the values into the table, you could have javascript calculate the values and write the table to the myvalue=5; MyValue=5; document. result=myvalue+myvalue; An example of a javascript generated table can be seen result=myvalue+MyValue; on the page explaining the hexadecimal colorsytem. document.write(result); On thatdocument.write(result); page, there are 15 tables with 25 columns in each. </script> </script> Each cell shows different mixtures of the basic colors red, green and blue. </body> </body> To set up these tables in HTML would demand almost an entire days work. Using javascript for the same </html> </html> purpose took less than 15 minutes! The output of example 1 would be 10 (5+5). The output of example 2 would be 7 (2+5). The best advice is to use the same syntax on all variables. Either write all variables in small letters, start with one capital letter or write all variables in capitals. Which syntax you chose is not important - as long as you chose just one!

POPUP BOX
It is possible to make three different kinds of popup windows. ALERT BOX The syntax for an alert box is: alert("yourtext"); The user will need to click "OK" to proceed. Typical use is when you want to make sure information comes through to the user. Examples could be warnings of any kind. (Typical examples are "Adult Content", or technical matters like "This site requires Shockwave Flash plug-in").

CONFIRM BOX: The syntax for a confirm box is: confirm("yourtext"); The user needs to click either "OK" or "Cancel" to proceed. Typical use is when you want the user to verify or accept something. Examples could be age verification like "Confirm that you are at least 57 years old" or technical matters like "Do you have a plug-in for Shockwave Flash?" - If the user clicks "OK", the box returns the value true. - If the user clicks "Cancel", the box returns the value false. if (confirm("Do you agree")) {alert("You agree")} else{alert ("You do not agree")};

Note: The if statement is explained later in this tutorial. PROMPT BOX: The prompt box syntax is: prompt("yourtext","defaultvalue"); The user must click either "OK" or "Cancel" to proceed after entering the text. Typical use is when the user should input a value before entering the page. Examples could be entering user's name to be stored in a cookie or entering a password or code of some kind. - If the user clicks "OK" the prompt box returns the entry. - If the user clicks "Cancel" the prompt box returns null. Since you usually want to use the input from the prompt box for some purpose it is normal to store the input in a variable, as shown in this example: username=prompt("Please enter your name","Enter your name here");

VARIABLES
Variables can be compared to small boxes with names. If you were to store 5 pair of shoes, you might have a box for each pair. On each box you would write what is in it. The boxes would be your variables. - Places to store things. The name on the boxes would be the variable names. - The ones you'd use when referring to each of the boxes.

And finally the shoes, would be the content of the variables. - What is stored in the boxes.

A variable is simply a place in the computer's memory to store information. All variables are referred to by the unique name you assigned to them. Consider this example: <html> <head> <title>My Javascript Page</title> </head>

<body> <script> myname="Henrik"; document.write(myname); </script> </body> </html>

This example would write "Henrik" in the document. Note that when you want text to be stored in a variable you need to put the text in " ". The reason is that javascript uses " " to tell the difference between text and variables. Look at this example to see the importance of this. <html> <head> <title>My Javascript Page</title> </head> <body> <script> Henrik="my first name"; myname=Henrik; document.write(myname); </script> </body> </html> Try to predict the output of the example before reading on. - In the first line, the text "my first name" is stored in the Henrik variable. - In the second line, the Henrik variable is stored in the myname variable. - Finally in line 3, the myname variable is written to the document. The result is that "my first name" will be written on the page. ASSIGNING VALUES TO VARIABLES The most common way to assign a value to a variable is using the equals sign. Consider these examples to see the different ways variables can be assigned to contain either values or text. Note in particular how parentheses can be used to control how complex formulas are handled. Example a=2; a=2; a++; a=2; a--; a=2; b=3; c=a+b; a=2; d=a+6; First="Henrik"; Last="Petersen"; Full=First+" "+Last; a=2*7; Resulting value a=2 a=3 (2+1) a=1 (2-1) c=5 (2+3) d=8 (2+6) First=Henrik Last=Petersen Full=Henrik Petersen a=14 (2*7)

b=20/5; c=(20/5)*2; d=20/(5*2);

b=4 (20/5) c=8 (4*2) d=2 (20/10)

ARITHMETHIC OPERATORS The above table includes the so-called "arithmethic operators" a++ and a--. You could really live well without these, since what they do can be achieved by using the other operators available. However you will often see them used in scripts, and you might even be lazy enough to use them yourself, since it is faster to type a++; than it is to type a=a+1;.

Operator Explanation ++ increment

--

decrement

returns modulus, which is what is left when two numbers are divided.

Example a=5; a++; a would now equal 6 a=5; a--; a would now equal 4 a=8 % 3; a would now equal 2, since 8 can be divided by 3 two times leaving a remainder of 2.

COMPARING VARIABLES There are several different ways to compare variables. The simplest is comparing for equality, which is done using a double equals sign: if (a==b) {alert("a equals b")}; if (lastname=="Petersen") {alert("Nice name!!!")}; Note: The if statement is explained in the next section. If you forget to use double equals signs when comparing variables for equality, and use a single equals sign instead, you will not compare the variables. What will happen is that the variable on the left side of the equals sign will be assigned the value of the variable to the right. An example of the error: if (lastname="Petersen") {alert("Nice name!!!")}; This is a very common bug that will totally ruin the script. This table contains the different comparing operators: Operator == Explanation equal to Example 4==5 (false) 5==5 (true) 5==4 (false) 4!=5 (true) 5!=5 (false) 5!=4 (true) 4<5 (true) 5<5 (false)

!= <

not equal to less than

>

greater than

<=

less than or equal to

>=

greater than or equal to

5<4 (false) 4>5 (false) 5>5 (false) 5>4 (true) 4<=5 (true) 5<=5 (true) 5<=4 (false) 4>=5 (false) 5>=5 (true) 5>=4 (true)

On the function page you will learn more about global and local variables. On the array page you will learn more about ways to work with large amounts of variables.

IF AND ELSE
Sometimes javascript requires the ability to make distinctions between different possibilities. For example, you might have a script that checks which browser the user arrives with. If it's MSIE, a page specifically designed for that browser should be loaded, if it's Netscape another page should be loaded. The general syntax for if statements is: if (condition) {action1} else {action2}; An example could be: if (browser=="MSIE") {alert("You are using MSIE")} else {alert("You are using Netscape")};

Again it is important to note that if is written as "if". Using the capital "IF" would cause an error. Also note that when comparing variables you will need to have two equals signs next to each other (==). If we wrote browser="MSIE" we would actually store "MSIE" in the variable called browser. When you write browser=="MSIE" javascript knows that you want it to compare rather than assign a value. The next section explains the different operators (=, <, > etc.). More complex if statements can be made by simply entering new if statements in the else part: if (condition) {action1} else {if (condition) {action2} else {action3};}; An example: if (browser=="MSIE") {alert("You are using MSIE")} else {if (browser=="Netscape") {alert("You are using Netscape")} else {alert("You are using an unknown browser")};}; AND, OR & NOT To further enhance your if statements you can use the so-called logical operators. And is written as && and is used when you want to check if more than one condition is true.

Ex: If the basket contains egg and the basket contains bacon, we can have egg and bacon. The syntax is: if (condition && condition) {action} if (hour==12 && minute==0) {alert("it's noon")}; Or is written as || and is used when more than a one condition should result in the check being true. (|| is achieved by using the shift key combined with the \ key) Ex: If the basket contains milk or the basket contains water, we can have something to drink. The syntax is: if (condition || condition) {action} if (hour==11 || hour==10) {alert("it's less than 2 hours till noon")}; Not is written as ! and is used to invert the result. Ex: If not the basket contains egg or not the basket contains bacon, we cant have egg and bacon. The syntax is: if (!(condition)) {action} if (!(hour==11)) {alert("it's more than 1 hour till noon")};

FUNCTION
Instead of just adding your javascript to the page and having the browser perform the tasks as soon as the script is read, you might want your javascript to be performed only upon the detection of a certain event. For example, if you made a javascript code that changed the background color of the page when the user clicked a button, then you would need to tell the browser, that the script should not be performed right away when loaded. To keep the browser from performing a script as soon as it is loaded you need to write the script as a function. Javascript written into functions will not be performed until you specifically ask for it. This way you gain complete control of the timing. Look at this example of script lines written as a function: <html> <head> <script> function myfunction() { alert("Welcome to my world!!"); } </script> </head> <body> <form name="myform"> <input type="button" value="Hit me" onclick="myfunction()"> </form> </body> </html>

The call of the function is in this line:

<input type="button" value="Click Here" onclick="myfunction()"> As you can see, we placed the button in a form and added the event onClick="myfunction()" to the properties of the button. The next page gives a detailed description of the different events you could use to trigger functions. The general syntax for a function is: function functionname(variable1, variable2,..., variableX) { // Here goes the javascript lines for the function } The { and the } marks the start and end of the function. A typical bug when entering javascript functions is to forget about the importance of capitals in javascript. The word function must be spelled exactly as function. Function or FUNCTION would cause an error. Furthermore, use of capitals matters in the name of the function as well. If you had a function called myfunction() it would cause an error if you referred to it as Myfunction(), MYFUNCTION() or MyFunction().

EVENTS
Events are actions that can be detected by javascript. An example would be the onmouseover event, which is detected when the user moves the mouse over an object. Another event is the onload event, which is detected as soon as the page is finished loading. Usually, events are used in combination with functions, so that the function does not start until the event happens. An example would be a function that would animate a button. The function simply shifts two images. One image that shows the button in an "up" position, and another image that shows the button in a "down" position. If this function is called using an onmouseover event, it will make it look as if the button is pressed down when the mouse is moved over the image. The following are the most important events recognized by javascript: Event onfocus="" onblur="" onchange="" onselect="" onmouseover="" onmouseout="" onclick="" onload="" onunload="" onSubmit="" Detected when Form field gets focus Form field looses focus Content of a field changes Text is selected Mouse moves over a link Mouse moves out of a link Mouse clicks an object radio, reset, submit Page is finished loading body, frameset Browser opens new document body, frameset Submit button is clicked form HTML tags select, text, textarea select, text, textarea select, text, textarea text, textarea A A A, button, checkbox,

Events are used for two main purposes:

To perform a function upon detection of the event, To show a popup box upon detection of the event.

Below is a brief description of the main purposes for each event. onFocus, onblur and onchange are mainly used in combination with validation of form fields. Lets say you had a function called validateEmail() that would check to see if an entered email address has an @ in it, and if it has a meaningful end, such as "com", "net" or whatever. Furthermore, suppose the user could enter his email address in a form. You would then use the onchange event to call the function whenever the user changes the content of the field: <input type="text" size="20" onchange="validateEmail()">; Click here to learn more about forms. Click here to learn more about form field validation. onload and onunload are mainly used for popups that appear when the user enters or leaves the page. Another important use is in combination with cookies that should be set upon arrival or leaving your pages. For example, you might have a popup asking the user to enter his name upon his first arrival to your page. The name is then stored in a cookie. Furthermore, when the visitor leaves your page a cookie stores the current date. Next time the visitor arrives at your page, it will have another popup saying something like: "Welcome Bill Clinton, this page has not been updated since your last visit 8 days ago". Click here to learn more about setting cookies. Click here to learn more about popup boxes. Another common use of the onLoad and onunload events is: Some annoying pages have a function that immediately opens several other windows as soon as you enter the page. This is a clear break of netiquette, and is not considered proper webdesign. onsubmit is used for one major purpose: To validate all fields within a form before actually submitting it. In the above example for onchange we showed how you can validate a single form field. Sometimes however, the visitor might find it annoying to have validations in the middle of entering fields on a form. Rather than validating after each input, you might want the form to be validated only upon clicking the submit button. This can be done using the onsubmit event. Assume you made a function named checkform() that would validate entries to a form. Now you want this function to be called when the user clicks the submit button. If the content is not accepted by your function the submit should be cancelled. This way nothing would be submitted unless your function accepted the content. What you should do, is: add an onsubmit event to the <form> tag this way: <form method="yourchoice" action="yourchoice" onsubmit="return checkform()">

The function checkform() returns either true or false. If it returns true the submit will take place. If it returns false the submit will be cancelled. Click here to learn more about forms. Click here to learn more about form validation.

onmouseover and onmouseout are mainly used for one purpose: To create animated buttons. You may have noticed that these events can only be used in combination with the link tag <a>. However, the events are often more useful in combination with the image tag <img>. The trick to making the event work on an image is simply to turn the image into a link. (If the image is not supposed to actually work as a link, you could always make it link to an empty anchor, as shown in the example below). Example: an alert box appears when an onmouseover is detected on an image:

The HTML from the example: <a href="#" onmouseover="alert('I detected an onmouseover event'); return false" onmouseout="alert('I detected an onmouseout event'); return false"> <img src="rainbow.gif" width="60" height="60"> </a>

LOOPS
Imagine that you wanted a script to perform the same routine over and over again 50 times in a row. An example could be if you wanted a script to produce a table comparing temperatures in Fahrenheit and Celsius. The script should produce 50 lines in a table showing different temperatures according to the two scales. Instead of adding 50 almost equal lines in your script you could use loops to make the script perform a task like this. There are two different kinds of loops: for and while. The for loop is used when you know in advance how many times the script should perform. For example if you wanted it to create exactly 50 lines. The while loop is used when you want the loop to continue until a certain condition becomes true. For example, if you wanted to make a table comparing Celsius and Fahrenheit, stepping 15 degrees for each row, and you wanted the table to contain values up to 1200 degrees of Celsius. Below is a description of each of these two loops: FOR LOOPS: SYNTAX: for (variable=startvalue; variable<=endvalue; variable=variable+incrementfactor) { // Here goes the script lines you want to loop. } Enter a variablename where it says variable. Enter the startvalue of the loop where it says startvalue. Enter the endvalue of the loop where it says endvalue. Enter the factor each loop should increment where it says incrementfactor. Note: The incrementfactor could be negative if you wanted.

Furthermore the <= could be any comparing statement, ex. >, == or whatever. EXAMPLE: <html> <head> <title>Celsius-Fahrenheit Converter</title> </head> <body> <table border=3> <tr><td>CELSIUS</td><td>FAHRENHEIT</td></tr> <script language="javascript"> for (celsius=0; celsius<=50; celsius=celsius+1) { document.write("<tr><td>"+celsius+"</td><td>" +((celsius*9/5)+32)+"</td></tr>"); } </script> </table> </body> </html> Click here to see the page from this example. WHILE LOOPS: SYNTAX: while (variable<=endvalue) { // Here goes the script lines you want to loop. } Enter a variablename where it says variable. Enter the endvalue of the loop where it says endvalue. Note: The <= could be anything that would fit the purpose ex. >, == or whatever. EXAMPLE: <html> <head> <title>Celsius-Fahrenheit converter</title> </head> <body> <table border=3> <tr><td>CELSIUS</td><td>FAHRENHEIT</td></tr> <script language="javascript"> celsius=0; while (celsius<=50) { document.write("<tr><td>"+celsius+ "</td><td>"+((celsius*9/5)+32)+"</td></tr>"); celsius=celsius+1;

} </script> </table> </body> </html> Click here to see the page from this example. BREAK & CONTINUE Two special commands can be used in loops: break and continue. break simply breaks the loop and continues with what might follow after the loop. An example would be if you had a loop calculate the squareroot of numbers decrementing from 50. Since calculating the square root of a negative number is an illegal mathemathic operation you would like the loop to end when the square root of zero had been calculated. To do this you would add this inside your loop: if (value==0) {break}; continue breaks the current loop and continues with the next value. An example would be if you had a loop that divided a certain value with a factor of numbers ranging from -50 to +50. Since division by zero is an illegal mathemathic procedure the loop would look like this: for (value=-50; value<=50; value=value+1) { if (value==0) {continue}; document.write((100/value)+"<br>"); }

POPUP WINDOWS
If you want a link to open a document in a new regular window you should not use javascript to do so. Instead you should simply add the property target="_blank" in the <a href> tag: <a href="http://www.yahoo.com" target="_blank">Go to Yahoo</a> This technique is explained in the HTML section. With javascript it is possible to open and close a new window in a much more powerful way. With javascript you can position and define the size of the pop up windows - so they don't just pop up with a random size at a random position, like they do if you open a new window in plain HTML. You will also learn to open windows where you decide which navigation buttons etc. that should be available to the user (if any). Proceed to get all the details!
JavaScript has built-in methods for opening and closing windows. The window.open method lets you open a new window in a much more powerful way than if you had opened it with plain HTML using target="blank". You can specify the size of the new window. Furthermore you can specify which browser buttons and menus etc. you want to appear in the new window. Finally you can even control the position of the new window.

When working with popup windows, three different techniques are relevant: HOW TO OPEN A WINDOW HOW TO CLOSE A WINDOW

HOW TO CUSTOMIZE A WINDOW

This page covers these techniques one by one. OPEN WINDOW The basic javascript to open a new window is: MyNewWindow= window.open("http://www.mydomain.com/myfile.html", "NameOfMyWindow"); This will open a new window similar to the one described on the previous page. We still haven't set any conditions for the size of the window or which of the browsers menus and buttons we want to be present. CLOSE WINDOW The javascript to close the window is: NameOfMyWindow.close(); NameOfMyWindow is the name you assigned to the window when you opened it. Note: If you want to close the current active window you do not need to specify the window name. Instead you can simply use: window.close(); CUSTOMIZING A WINDOW You can add several parameters for the new window. This will allow you to control the size as well as which parts of the browser should be available in the window. option toolbar = yes | no location = yes | no directories = yes | no status = yes | no menubar = yes | no scrollbars = yes | no resizeable = yes | no width = value height = value explanation add/remove browsers toolbar add/remove browsers location field add/remove browsers directories field add/remove browsers status field add/remove browsers menubar add/remove browsers scrollbars allow new window to be resizable window width in pixels window height in pixels

An example showing the way to define which parts of the browser should be visible is shown below: PageURL="http://www.mydomain.com/myfile.html"; WindowName="MyPopUpWindow";

settings= "toolbar=yes,location=yes,directories=yes,"+ "status=no,menubar=no,scrollbars=yes,"+ "resizable=yes,width=600,height=300"; MyNewWindow= window.open(PageURL,WindowName,settings); Note: There are no spaces between the settings. If you add spaces here, the window will not open correctly in Netscape browsers.
This is a ready to use script that will allow you to easily open new windows on your pages. You can customize the script using the information in the preceeding section. The script needs to be placed in the <head> section of your HTML document. <script Language="JavaScript"> <!-function popup(url, name, width, height) { settings= "toolbar=yes,location=yes,directories=yes,"+ "status=no,menubar=no,scrollbars=yes,"+ "resizable=yes,width="+width+",height="+height; MyNewWindow=window.open("http://"+url,name,settings); } //--> </script> Once the script is added to your page, you can open windows using this syntax for the link tags: <a href="#" onClick="popup('www.yahoo.com', 'Win1', 300, 300); return false"> Click Here To Go to Yahoo</a> If you don't want to use the ready to use script in the previous section, click here to go to the Popup Windows Tool. Note: In the example, we named the window "MyWindow".If you have more than one popup window on the same page, you need to rename the window names. Use for example "MyWindow1", "MyWindow2" etc.

EXAMPLE

FORM VALIDATION

Javascript is a strong tool for validating forms before sending the content. The most obvious things to check for are whether an emailaddress has valid syntax, or if fields meant for values have text entered, etc. This page covers the 4 most important techniques. Consider this form: EMAIL: VALUE (0-5): VALUE (Integer, 3-4 digits): Do not leave this field empty: Note: The form is not activated - Try entering values to see what happens. The javascript to validate inputs to a form consists of four different functions:

emailvalidation will check to see if a value lives up to the general syntax of an email.

valuevalidation will check to see if a value is within a certain interval.

digitvalidation will check to see if a value consits of a certain number of digits.

emptyvalidation will check to see if a field is empty or not.

The validation can take place as the visitor enters values, or all at once upon clicking the submit button after entering the values. Each validation function can easily be customized to fit the needs of the fields they are checking. The script explained on this page actually consists of the four functions listed below: emailvalidation(this,text) valuevalidation(this,min,max,text,type)

digitvalidation(this,min,max,text,type) emptyvalidation(this,text)

You can either validate each field whenever it is changed or you can validate all fields at one time when the submit button is clicked.

At the last half of this page you can learn how to use either of these methods along with the scripts. First, let's look at the different validation scripts. emailvalidation(this,text) Checking if the content has the general syntax of an email. Optional parameters are: text--text that will show in an alertbox if content is illegal. function emailvalidation(entered, alertbox) { // E-mail Validation by Henrik Petersen / NetKontoret // Explained at www.echoecho.com/jsforms.htm // Please do not remove this line and the two lines above. with (entered) { apos=value.indexOf("@"); dotpos=value.lastIndexOf("."); lastpos=value.length-1; if (apos<1 || dotpos-apos<2 || lastpos-dotpos>3 || lastpos-dotpos<2) {if (alertbox) {alert(alertbox);} return false;} else {return true;} } }

valuevalidation(this,min,max,text,type) Checking if the content is a number in a limited area. Optional parameters are: min --minimum value allowed in the field. max --maximum value allowed in the field. text --text that will show in an alertbox if content is illegal. type --enter "I" if only integers are allowed. function valuevalidation(entered, min, max, alertbox, datatype) { // Value Validation by Henrik Petersen / NetKontoret // Explained at www.echoecho.com/jsforms.htm // Please do not remove this line and the two lines above. with (entered) { checkvalue=parseFloat(value); if (datatype) {smalldatatype=datatype.toLowerCase(); if (smalldatatype.charAt(0)=="i") {checkvalue=parseInt(value)}; } if ((parseFloat(min)==min && checkvalue<min) || (parseFloat(max)==max && checkvalue>max) || value!=checkvalue) {if (alertbox!="") {alert(alertbox);} return false;} else {return true;} } }

digitvalidation(this,min,max,text,type) Checking if the content has a certain number of digits. Optional parameters are: min --minimum number of digits allowed in the field. max --maximum number of digits allowed in the field. text --text that will show in an alertbox if content is illegal. type --enter "I" if only integers are allowed. function digitvalidation(entered, min, max, alertbox, datatype) { // Digit Validation by Henrik Petersen / NetKontoret // Explained at www.echoecho.com/jsforms.htm // Please do not remove this line and the two lines above. with (entered) { checkvalue=parseFloat(value); if (datatype) {smalldatatype=datatype.toLowerCase(); if (smalldatatype.charAt(0)=="i") {checkvalue=parseInt(value); if (value.indexOf(".")!=-1) {checkvalue=checkvalue+1}}; } if ((parseFloat(min)==min && value.length<min) || (parseFloat(max)==max && value.length>max) || value! =checkvalue) {if (alertbox!="") {alert(alertbox);} return false;} else {return true;} } }

emptyvalidation(this,text) Checking if the field is empty. Optional parameters are: text --text that will show in an alertbox if content is illegal. function emptyvalidation(entered, alertbox) { // Emptyfield Validation by Henrik Petersen / NetKontoret // Explained at www.echoecho.com/jsforms.htm // Please do not remove this line and the two lines above. with (entered) { if (value==null || value=="") {if (alertbox!="") {alert(alertbox);} return false;} else {return true;} } }

Note: All functions require this to be entered as a parameter. Simply enter the word "this" as a parameter when calling one of the functions. This will pass the content of the current field to the function. If text is not entered when you call the function, it will not launch a popup box if an error is detected. However, the function will still return the value "false". This option is used when we check for several possible errors at one time. That is: when all fields are checked once the submit button is clicked. USING THE VALIDATION SCRIPTS There are two different ways to call these functions. One is used when you want to check the field immediately after an input is made to it. The other is when you want to check all fields at one time, when the user clicks the submit button. onChange Validation: To force the browser to check each field immediately, we add an onChange to each of the <input> tags in the form. For example: if we wanted to check if the value of a certain text field had a valid e-mail address we would add this: <input type="text" name="Email" size="20" onChange="emailvalidation(this,'The E-mail is not valid');"> onSubmit Validation You might prefer to check all fields at one time when the user hits the submit button. To do this you should add an onSubmit event handler to the <form>tag. If, for example you have a form called "myform" and you want all fields checked when the user clicks 'submit' you should create a function that checks all the fields. This function should then be called by an onSubmit-event added to the <form> tag. If this function was called "formvalidation()" the <form> tag would look like this: <form onsubmit="return formvalidation(this)"> The function that checks the entire form will either return a value of false or true. If it's true the form will be submitted - if it's false the submission will be cancelled. A script that checks all fields in a form could look like this: function formvalidation(thisform) This function checks the entire form before it is submitted. function formvalidation(thisform) { with (thisform) { if (emailvalidation(Email,"Illegal E-mail")==false) {Email.focus(); return false;}; if (valuevalidation(Value,0,5,"Value MUST be in the range 05")==false) {Value.focus(); return false;}; if (digitvalidation(Digits,3,4,"You MUST enter 3 or 4 integer

digits","I")==false) {Digits.focus(); return false;}; if (emptyvalidation(Whatever,"The textfield is empty")==false) {Whatever.focus(); return false;}; } } Note: The above function works in addition to the four functions listed at the top of this page. Furthermore, the function needs to be customized to fit your form. You will need to enter the appropriate form field names used on your own form. (Instead of "E-mail", "Value", "Digits" and "Whatever" in this example). Furthermore you would need to call the appropriate functions depending on which check you would like to perform on each form field. (In the example each field is checked by a different function. You could as well have each field checked by the same function. If for example the form had 4 fields that should all contain an e-mail address you would add an emailvalidation to each. )
EXAMPLE

THE ENTIRE SCRIPT If you want to use all four validation scripts and the script that will check all fields at once, feel free to copy the entire code listed below to your page. Note: The function called formvalidation() needs to be customized to fit your own form. <script> function emailvalidation(entered, alertbox) { // E-mail Validation by Henrik Petersen / NetKontoret // Explained at www.echoecho.com/jsforms.htm // Please do not remove this line and the two lines above. with (entered) { apos=value.indexOf("@"); dotpos=value.lastIndexOf("."); lastpos=value.length-1; if (apos<1 || dotpos-apos<2 || lastpos-dotpos>3 || lastpos-dotpos<2) {if (alertbox) {alert(alertbox);} return false;} else {return true;} } } function valuevalidation(entered, min, max, alertbox, datatype) { // Value Validation by Henrik Petersen / NetKontoret // Explained at www.echoecho.com/jsforms.htm // Please do not remove this line and the two lines above. with (entered)

{ checkvalue=parseFloat(value); if (datatype) {smalldatatype=datatype.toLowerCase(); if (smalldatatype.charAt(0)=="i") {checkvalue=parseInt(value)}; } if ((parseFloat(min)==min && checkvalue<min) || (parseFloat(max)==max && checkvalue>max) || value!=checkvalue) {if (alertbox!="") {alert(alertbox);} return false;} else {return true;} } } function digitvalidation(entered, min, max, alertbox, datatype) { // Digit Validation by Henrik Petersen / NetKontoret // Explained at www.echoecho.com/jsforms.htm // Please do not remove this line and the two lines above. with (entered) { checkvalue=parseFloat(value); if (datatype) {smalldatatype=datatype.toLowerCase(); if (smalldatatype.charAt(0)=="i") {checkvalue=parseInt(value); if (value.indexOf(".")!=-1) {checkvalue=checkvalue+1}}; } if ((parseFloat(min)==min && value.length<min) || (parseFloat(max)==max && value.length>max) || value! =checkvalue) {if (alertbox!="") {alert(alertbox);} return false;} else {return true;} } } function emptyvalidation(entered, alertbox) { // Emptyfield Validation by Henrik Petersen / NetKontoret // Explained at www.echoecho.com/jsforms.htm // Please do not remove this line and the two lines above. with (entered) { if (value==null || value=="") {if (alertbox!="") {alert(alertbox);} return false;} else {return true;} } }

function formvalidation(thisform) { // This function checks the entire form before it is submitted // Note: This function needs to be customized to fit your form with (thisform) { if (emailvalidation(Email,"Illegal E-mail")==false) {Email.focus(); return false;}; if (valuevalidation(Value,0,5,"Value MUST be in the range 05")==false) {Value.focus(); return false;}; if (digitvalidation(Digits,3,4,"You MUST enter 3 or 4 integer digits","I")==false) {Digits.focus(); return false;}; if (emptyvalidation(Whatever,"The textfield is empty")==false) {Whatever.focus(); return false;}; } } </script>

You might also like