Beginning with JavaScript

Vinay Kumar

JavaScript is a new scripting language, which is being developed by Netscape. With JavaScript you can easily create interactive web-pages. This tutorial shows you what can be done with JavaScript - and more importantly how it is done.

Running JavaScript

What is needed in order to run scripts written in JavaScript? You need a JavaScript-enabled browser. Since Web browsers are widely spread many people are able to run scripts written in JavaScript. This is certainly an important point for choosing JavaScript to enhance your web-pages. Of course you need a basic understanding of HTML before reading this tutorial.

Embedding JavaScript into a HTML-page

JavaScript code is embedded directly into the HTML-page. In order to see how this works we are going to look at an easy example:

<html>
<body>
<br>
This is a normal HTML document.
<br>
<script language="JavaScript"> document.write("Welcome to JavaScript!") </script> <br> Back in HTML again. </body> </html>

At the first glance this looks like a normal HTML-file. The only new thing is the part:

<script language="JavaScript">
document.write("Welcome to JavaScript!")
</script> 

Welcome to JavaScript. In order to see this script working save this code as a normal HTML-file and load it into your JavaScript-enabled browser. Here is the output generated by the file (if you are using a JavaScript browser you will see 3 lines of output):

This is a normal HTML document.
Welcome to JavaScript!
Back in HTML again.

I must admit that this script isn’t very useful - this could have been written in pure HTML more easily. I only wanted to demonstrate the <script> tag to you. Everything between the <script> and the </script> tag is interpreted as JavaScript code. There you see the use of document.write() - one of the most important commands in JavaScript programming. document.write() is used in order to write something to the actual document (in this case this is the HTML-document). So our little JavaScript program writes the text This is JavaScript! to the HTML-document.

Non-JavaScript browsers

What does our page look like if the browser does not understand JavaScript? A non-JavaScript browser does not know the <script> tag. It ignores the tag and outputs all following code as if it was normal text. This means the user will see the JavaScript-code of our program inside the HTML-document. This was certainly not our intention. There is a way for hiding the source code from older browsers. We will use the HTML-comments <!-- -->. Our new source code looks like this:

<html>
<body>
<br>
This is a normal HTML document.
<br>
<script language="JavaScript"> <!-- hide from old browsers document.write("Welcome to JavaScript!!")
// --> </script> <br> Back in HTML again. </body> </html>

The output in a non-JavaScript browser will then look like this:

This is a normal HTML document.
Back in HTML again.

Without the HTML-comment the output of the script in a non-JavaScript browser would be:

This is a normal HTML document.
document.write("Welcome to JavaScript!!")
Back in HTML again.

Please note that you cannot hide the JavaScript source code completely. What we do here is to prevent the output of the code in old browsers - but the user can see the code through ’View document source’ nevertheless. There is no way to hinder someone from viewing your source code (in order to see how a certain effect is done).

Events

Events and event handlers are very important for JavaScript programming. Events are mostly caused by user actions. If the user clicks on a button a Click-event occurs. If the mousepointer moves across a link a MouseOver-event occurs. There are several different events. We want our JavaScript program to react to certain events. This can be done with the help of event-handlers. A button might create a popup window when clicked. This means the window should pop up as a reaction to a Click-event. The event-handler we need to use is called onClick. This tells the computer what to do if this event occurs. The following code shows an easy example of the event-handler onClick:

<form>
<input type="button" value="Click me" onClick="alert(’Yo’)">
</form>

Functions

We will use functions in most of our JavaScript programs. Therefore we will talk about this important concept. Basically functions are a way for bundling several commands together. Let’s write a script, which outputs a certain text three times. Consider the following approach:

<html>
<script language="JavaScript">
<!-- hide
document.write("Welcome to website!<br>");
document.write("Welcome to  JavaScript!<br>");
document.write("Welcome to website!<br>");
document.write("Welcome to  JavaScript!<br>");
document.write("Welcome to website!<br>");
document.write("Welcome to  JavaScript!<br>");
// -->
</script>
</html>

This will write out the text
Welcome to website!
Welcome to JavaScript!

three times. Look at the source code - writing the code three times brings out the right result. But is this very efficiently? No, we can solve this better. How about this code which does the same:

<html>
  <script language="JavaScript">
  <!-- hide
      function myFunction() {
      document.write("Welcome to my  homepage!<br>");
      document.write("This is JavaScript!<br>");

 

} myFunction(); myFunction(); myFunction(); // -->
</script> </html>

In this script we define a function. This is done through the lines:

function myFunction() {
document.write("Welcome to my  homepage!<br>");
document.write("This is JavaScript!<br>");
}


The commands inside the {} belong to the function myFunction(). This means that our two document. write() commands are bundled together and can be executed through a function call. Inour example we have three function calls. You can see that we write myFunction() three timesjust below the definition of the function. These are the three function calls. This means that the contents of the function is being executed three times. This is a very easy example of a function. You might wonder why functions are so important. While reading this tutorial you will certainly realize the benefits of functions. Especially variable passing makes our scripts really flexible - we will see what this is later on. Functions can also be used in combination with event-handlers. Please consider this example:

<html>
<head>
<script language="JavaScript">
<!-- hide
function calculation() {
var x= 27;
var y= 7;
var result= x + y;
alert(result);
}
// -->
</script>

</head> <body> <form> <input type="button" value="Calculate" onClick="calculation()">
</form> </body> </html>


The location-object

Besides the window- and document-objects there is another important object: the location-object. This object represents the address of the loaded HTML-document. So if you loaded the page http://www.abc.com/page.html then location.href is equal to this address. What is more important is that you can assign new values to location.href. This button for example loads a new page into the actual window:

<form>
<input type=button value="Rediff"
onClick="location.href=’http://www.rediff.com’;  ">
</form>

 

Creating frames

An often asked question is how frames and JavaScript work together. First I want to explain what frames are and what they can be used for. After this we will see how we can use JavaScript in combination with frames. The browser window can be split up into several frames. This means a frame is a square area inside the browser window. Each frame displays its own document (most of the time HTML-documents). So you can for example create two frames. In the first frame you load the homepage of Firefox and in the second frame you load the homepage of Microsoft. Although creating frames is a HTML-problem I want to describe the basic things.

For creating frames you need two tags: <frameset> and <frame>. A HTML-page creating two frames might look like this:

<html>
<frameset rows="50%,50%">
<frame src="page1.htm"  name="frame1">
<frame src="page2.htm"  name="frame2">
</frameset>
</html>



This will produce two frames. You can see that we use the rows property in the <frameset> tag. This means the two frames lie above each other. The upper frame loads the HTML-page page1.htm and the lower frame displays the document page2.htm. The created frame-structure looks like this:

 



calculate how large the second frame must be in order to get 100%. You
can specify the size in pixels by omitting the % symbol. Every frame gets an unique name with the name property in the <frame> tag. This will help us when accessing the frames through JavaScript.

You can have several nested <frameset> tags. (I just modified it a little bit):

<frameset cols="50%,50%">
<frameset rows="50%,50%">
<frame src="cell.htm">
<frame src="cell.htm">
</frameset>
<frameset rows="33%,33%,33%">
<frame src="cell.htm">
<frame src="cell.htm">
<frame src="cell.htm">
</frameset>
</frameset>

The created frame structure looks like this:




Navigationbars

Now we will take a look at a navigationbar. We will have several links in one frame. If the user clicks on these links the pages won’t show up in the same frame - they are loaded in the second frame. First we need a script which creates the frames. This document looks like the first example we had in this part:

frames3.htm
<html> <frameset rows="80%,20%"> <frame src="start.htm" name="main"> <frame src="menu.htm" name="menu"> </frameset> </html>

The start.htm page is the entry page which will be displayed in the main frame at the beginning. There are no special requirements for this page. The following page is loaded into the frame menu:

menu.htm
<html> <head> <script language="JavaScript"> <!-- hide function load(url) { parent.main.location.href= url; }
// -->
</script> </head> <body>
<a href="javascript:load(’first.htm’)">first</a> <a href="second.htm" target="main">second</a> <a href="third.htm" target="_top">third</a> </body> </html>

Here you can see different ways for loading a new page into the frame main. The first link uses the function load(). Have a look at how this function is called:

<a href="javascript:load(’first.htm’)">first</a>

You can see that we can let the browser execute JavaScript code instead of loading another page we just have to use javascript: in the href property. You can see that we write ’first.htm’ inside the brackets. This string is passed to the function load(). The function load() is defined through:

function load(url) {
parent.main.location.href= url;
}

There you can see that we write url inside the brackets. This means that the string ’first1.htm’ is stored in the variable url. Inside the load() function we can now use this variable. The second link uses the target property. Actually this isn’t JavaScript. This is a HTML-feature. You see that we just have to specify the name of the frame. Please note that we must not put parent before the name of the frame. This might be a little bit confusing. The reason for this is that target is HTML and not JavaScript. The third link shows you how to remove the frames with the target property.

If you want to remove the frames with the load() function you just have to write parent.location. href= url inside the function. So which way should you choose? This depends on your script and what you want to do. The target property is very simple. You might use it if you just want to load the page in another frame.

The JavaScript solution (i.e. the first link) is normally used if you want to do several things as a reaction to the click on the link. One common problem is to load two pages at once in two different frames. Although you could solve this with the target property using a JavaScript function is more straightforward. Let’s assume you have three frames called frame1,frame2 and frame3. The user clicks on a link in frame1. Then you want to load two different pages in the two other frames. You can use this function for example:

function loadtwo() {
parent.frame1.location.href= "first.htm";
parent.frame2.location.href= "second.htm";
}

If you want to keep the function more flexible you can use variable passing here as well. This looks like this:

function loadtwo(url1, url2) {
parent.frame1.location.href= url1;
parent.frame2.location.href= url2;
}

Then you can call this function with loadtwo("first.htm", "second.htm") or loadtwo("third.htm", "forth.htm"). Variable passing makes your function more flexible. You can use it over and over again in different contexts.

Opening new browser windows is a great feature of JavaScript. You can either load a new document (for example a HTML-document) to the new window or you can create new documents (on-the-fly). We will first have a look at how we can open a new window, load a HTML-page to this window and then close it again. The following script opens a new browser window and loads a meaningless page:

<html>
<head>
<script language="JavaScript">
<!-- hide
function open_window() {
myWin= open("new_window.htm");
}
// -->
</script>
</head> <body> <form> <input type="button" value="Open new window" onClick=" open_window()">
</form> </body> </html>


The page new_window.htm is loaded into the new window through the open() method.
You can control the appearance of the new window. For example you can decide if the window shall have a statusbar, a toolbar or a menubar. Besides that you can specify the size of the window.

The following script opens a new window which has got the size 500x250. The window
does not have a statusbar, toolbar or menubar.

<html>
<head>
<script language="JavaScript">
<!-- hide
function open_window2() {
myWin= open("new_window.htm",  "displayWindow",
"width=500,height=250,status=no,toolbar=no,menubar=no");
}
// -->
</script> </head> <body> <form> <input type="button" value="Open new window" onClick=" open_window2">
</form> </body> </html>



You can see that we specify the properties in the string "width=500,height=250,status=no,toolbar=no,menubar=no".

Please note that you must not use spaces inside this string!

 

The name of a window

As you have seen we have used three arguments for opening a window:

myWin= open("new_window.htm", "displayWindow",
"width=500,height=250,status=no,toolbar=no,menubar=no");

What is the second argument for? This is the name of the window. We have seen how to use the target-property earlier. If you know the name of an existing window you can load a new page to it with

<a href="new_window.html" target="displayWindow">

Here you need the name of the window (if the window does not exist, a new window is created through this code). Please note that myWin is not the name of the window. You can just access the window through this variable. As this is a normal variable it is only valid inside the script in which it is defined. The window name (here displayWindow) is a unique name which can be used by all existing browser windows.

Closing windows

You can close windows through JavaScript. For this you need the close() method. Let’s open a new window as shown before. In this window we load the following page:

<html>
<script language="JavaScript">
<!-- hide
function closeIt() {
close();
}
// -->
</script>
innerHeight number of pixels (replaces height)
outerWidth number of pixels outerHeight number of pixels screenX position in pixels screenY position in pixels titlebar yes|no z-lock yes|no <center> <form> <input type=button value="Close it" onClick="closeIt()">
</form> </center> </html>

If you hit the button in the new window the window is being closed. open() and close() are methods of the window-object. Normally we should think that we have to write window.open() and window.close() instead of open() and close(). This is true - but the window-object is an exception here. You do not have to write window if you want to call a method of the window-object. (this is only true for this object).

Creating documents on-the-fly

We are coming now to a cool feature of JavaScript - creating documents on-the-fly. This means you can let your JavaScript code create a new HTML-page. You can output these documents in a separate window or in a frame.

First we will create a simple HTML-document, which will be displayed in a new window. Here is the script we are going to have a look at now.

<html>
<head>
<script language="JavaScript">
<!-- hide
function open_window() {
myWin= open("", "displayWindow",
"width=500,height=250,status=yes,toolbar=yes,menubar=yes");
// open document for further output
myWin.document.open();
// create document
myWin.document.write("<html><head><title>On-the-fly"); myWin.document.write("</title></head><body>"); myWin.document.write("<center><font size=+3>"); myWin.document.write("This HTML-document has been created "); myWin.document.write("with the help of JavaScript!"); myWin.document.write("</font></center>");
myWin.document.write("</body></html>"); // close the document - (not the window!) myWin.document.close(); }
// --> </script> </head> <body> <form>
<input type=button value="On-the-fly" onClick="open_window()"> </form> </body> </html>


Let’s have a look at the function open_window (). You can see that we open a new browser window first. As you can see the first argument is an empty string "" - this means we do not specify an URL. The browser should not just fetch an existing document - JavaScript shall create a new document.  We define the variable myWin. With the help of this variable we can access the new window. Please note that we cannot use the name of the window (displayWindow) for this task. After opening the window we have to open the document. This is done through:

// open document for further output
myWin.document.open();

We call the open() method of the document-object - this is a different method than the open() method of the window-object! This command does not open a new window - it prepares the document for further output. We have to put myWin before the document.open() in order to access the new window.

The following lines create the document with document.write():

// create document
myWin.document.write("<html><head><title>On-the-fly");
myWin.document.write("</title></head><body>");
myWin.document.write("<center><font size=+3>");
myWin.document.write("This HTML-document has been created ");
myWin.document.write("with the help of JavaScript!");
myWin.document.write("</font></center>");
myWin.document.write("</body></html>");

You can see that we write normal HTML-tags to the document. We create HTML-code! You can write any HTML-tags here.

After the output we have to close the document again. The following code does this:

// close the document - (not the window!)
myWin.document.close();

As we told you before you can create documents on-the-fly and display them in a frame as well. If you for example have got two frames with the names frame1 and frame2 and want create a new document in frame2 you can write the following in frame1:

parent.frame2.document.open();
parent.frame2.document.write("Here goes your HTML-code");
parent.frame2.document.close();

 

 

Statusbar and timeouts


The statusbar

Your JavaScript programs can write to the statusbar - this is the bar at the bottom of your browser window. All you have to do is to assign a string to window.status. The following example shows you two buttons which can be used to write to the statusbar and to erase the text again.

<html>
<head>
<script language="JavaScript">
function statbar(txt) {
window.status = txt;
}
</script> </head> <body> <form> <input type="button" name="look" value="Write!" onClick="statbar('Hi! This is the statusbar!');"> <input type="button" name="erase" value="Erase!" onClick="statbar('');"> </form> </body> </html>


We create a form with two buttons. Both buttons call the function statbar(). You can see that the function call created by the Write! button looks like this:

statbar('Hi! This is the statusbar!');

Inside the brackets we specify the string ’Hi! This is the statusbar!’ This means this string is passed along to the function statbar(). You can see that we defined the function

statbar() like this:
function statbar(txt) {
window.status = txt;
}

What is new is that we use txt inside the brackets of the function name. This means the string we passed along to the function is stored in the variable txt. Passing variables to functions is an often used way for making functions more flexible. You can pass several values to functions you just have to separate them through commas. The string txt is displayed on the statusbar through window.status = txt. Erasing the text on the statusbar is achived through assigning an empty string to window.status.

Displaying text on the statusbar can easily be used in combination with links. Instead of
showing the URL of the link you can explain in words what the next page is about. This link demonstrates this - just move your mousepointer over the link. The code for this example looks like this:

<a href="noclck.htm"
onMouseOver="window.status=’Do not click me!’; return true;"
onMouseOut="window.status=’’;">link</a>

Here we are using onMouseOver and onMouseOut in order to detect when the mousepointer moves across the link. You might wonder why we have to write return true inside the on- MouseOver property. This means that the browser won’t execute its own code as a reaction to the MouseOver event. Normally the browser displays the URL of the link in the statusbar.

Timeouts

With the help of timeouts (or timer) you can let the computer execute some code after a certain period of time. The following script shows a button which opens up a popup window after 5 seconds.

The script looks like this:
      
<script language="JavaScript"> <!-- hide function timer() { setTimeout("alert(’Time is up!’)", 5000); }
// --> </script> ... <form> <input type="button" value="Timer" onClick="timer()">
</form>


setTimeout() is a method of the window-object. It sets a timeout - I think you might have guessed that. The first argument is the JavaScript code which shall be executed after a certain time. In our case this argument is "alert(’Time is up!’)". Please note that the JavaScript code has to be inside quotes. The second argument tells the computer when the code shall be executed. You have to specify the time in number of milliseconds (5000 milliseconds = 5 seconds).

 

Scroller

Now that you know how to write to the statusbar and how timeouts work we will have a look at scrollers. You might already know the moving text-strings in the statusbar. They can be seen all over the Internet. We will see how to program a basic scroller. Besides that we will think of possible improvements of the scroller. Scrollers are quite easy to implement. Just let us think about how we could realize a moving text in the statusbar. We have to write a text to the statusbar. After a short period of time we have to write the same text to the statusbar - but we have to move it a little bit to the left side. If we repeat this over and over again the user gets the impression of a moving text. We have to think about how we can determine which part of the text should be displayed as the whole text is normally longer than the statusbar.

Here is the source code - We have added some comments:

<html>
<head>
<script language="JavaScript">
<!-- hide
// define the text of the scroller var scrtxt = "This is JavaScript! " + "This is JavaScript! " + "This is JavaScript!";
var length = scrtxt.length; var width = 100; var pos = -(width + 2); function scroll() { // display the text at the right position and set a timeout // move the position one step further pos++; // calculate the text which shall be displayed
var scroller = ""; if (pos == length) { pos = -(width + 2); }
// if the text hasn’t reached the left side yet we have to // add some spaces - otherwise we have to cut of the first // part of the text (which moved already across the left border

if (pos < 0) { for (var i = 1; i <= Math.abs(pos); i++) { scroller = scroller + " ";} scroller = scroller + scrtxt.substring(0, width - i + 1); }
else { scroller = scroller + scrtxt.substring(pos, width + pos); }
// assign the text to the statusbar window.status = scroller; // call this function again after 200 milliseconds setTimeout("scroll()", 200); }
// --> </script>
</head>

<body onLoad="scroll()"> Your HTML-page goes here.
</body> </html>


The main part of the scroll() function is needed for calculating which part of the text is being displayed. We are not explaining the code in detail - you just have to understand how this scroller works in general. In order to start the scroller we are using the onLoad event-handler of the <body> tag. This means the function scroll() will be called right after the HTML-page has been loaded. We call the scroll() function with the onLoad property. The first step of the scroller is being calculated and displayed. At the end of the scroll() function we set a timeout. This causes the scroll() function to be executed again after 200 milliseconds. The text is moved one step forward and another timeout is set. This goes on forever.

Scrollers are used widely in the Internet. There is the risk that they get unpopular quickly. We must admit that we do not like them too much. Especially annoying on most pages is that the URL cannot be read anymore when moving the pointer across a link. This can be solved through stopping the scroller when a MouseOver event occurs - you can start it again with onMouseOut. If you want to have a scroller try not to use the standard scroller  try to add some nice effect. Maybe one part of the text moving from left and the other part is coming from right - when they meet in the middle the text stands still for some seconds. With some phantasy you can certainly find some nice alternatives.

 

Validating form input

Forms are widely used on the Internet. The form input is often being sent back to the server or via mail to a certain e-mail account. But how can you be certain that a valid input was done by the user? With the help of JavaScript the form input can easily be checked before sending it over the Internet. First I want to demonstrate how forms can be validated. Then we will have a look at the possibilties for sending information over the Internet. First of all we want to create a simple script. The HTML-page shall contain two text-elements. The user has to write his name into the first and an e-mail address into the second element. If the user has entered his name (for example ‘Krishna’) into the first text-field the script creates a popup window with the text ‘Hi Krishna!’.

Concerning the first input element you will receive an error message when nothing is entered. Any input is seen as valid input. Of course, this does not prevent the user from entering any wrong name. The browser even accepts numbers. So if you enter '33' you will get 'Hi 33!'. So this might not be a good check. The second form is a little bit more sophisticated. Try to enter a simple string - your name for example. It won't work (unless you have a @ in your name...). The criteria for accepting the input as a valid e-mail address is the @. A single @ will do it – but this is certainly not very meaningful. Every Internet e-mail address contains a @ so it seems appropriate to check for a @ here.

What does the script for those two form elements and for the validating look like? Here it goes:

<html>
<head>
<script language="JavaScript">
<!-- Hide
function test1(form) {
if (form.text1.value == "") alert("Please enter a string!") else {
alert("Hi "+form.text1.value+"! Form input ok!");
}
}
function test2(form) { if (form.text2.value == "" || form.text2.value.indexOf(’@’, 0) == -1) alert("No valid e-mail address!");
else alert("OK!"); } // -->
</script>
</head> <body>
<form name="first"> Enter your name:<br> <input type="text" name="text1"> <input type="button" name="button1" value="Test Input" onClick="test1(this.form)">
<P>
Enter your e-mail address:<br> <input type="text" name="text2"> <input type="button" name="button2" value="Test Input" onClick="test2(this.form)">
</body>
</html>

First have a look at the HTML-code in the body-section. We just create two text elements and two buttons. The buttons call the functions test1(...) or test2(...) depending on which button is pressed. We pass this.form to the functions in order to be able to address the right elements in the functions later on. The function test1(form) tests if the string is empty. This is done via if (form.text1.value == "")... . ’form’ is the variable which receives the ’this.form’ value in the function call. We can get the value of the input element through using ’value’ in combination with form.text1. In order to look if the string is empty we compare it with "". If the input string equals "" then no input was done. The user will get an error message. If something is entered the user will get an ok.

The problem here is that the user might enter only spaces. This is seen as a valid input! If you want to, you can of course check for these possibilities and exclude them. I think this is quite easy with the information given here. Now have a look at the test2(form) function. This function again compares the input string with the empty string "" to make sure that something has been entered. But we have added something to the if-command. The || is called the OR-operator. The if-command checks if either the first or the second comparison is true. If at least one of them is true the whole if-command gets true and the following command will be executed. This means that you will get an error message either if your string is empty or if there isn’t a @ in your string. The second operation in the if-command looks if the entered string contains a @.

Checking for certain characters

Sometimes you want to restrict the form input to certain characters or numbers. Just think of a telephone number - the input should only contain digits (we assume that the telephone number does not contain any characters). We could check if the input is a number. But most people use different symbols in their telephone number - for example:

01234-56789, 01234/56789 or 01234 56789 (with a space inbetween). The user should not be forced to enter the telephone number without these symbols. So we have to extend our script to check for digits and some symbols. This is demonstrated in the next example:

<html>
<head>
<script language="JavaScript">
function check(input) {
var ok = true;
for (var i = 0; i < input.length; i++) {
var chr = input.charAt(i);
var found = false;
for (var j = 1; j < check.length; j++) {
if (chr == check[j]) found = true;
}
if (!found) ok = false;
}
return ok;
}
function test(input) {
if (!check(input, "1", "2", "3", "4",
"5", "6", "7", "8", "9", "0", "/", "-", " ")) {
alert("Input not ok.");
}
else {
alert("Input ok!");
}
}
// -->
</script>
</head>
<body>
<form>

Telephone:

<input type="text" name="telephone" value="">
<input type="button" value="Check"
onClick="test(this.form.telephone.value)">
</form>
</body>
</html>

 



The function test() specifies which characters are valid.

Submitting form input

What different possibilities do exist for submitting form input? The easiest way is to submit the form input via e-mail. This is the method we are going to look at a little bit closer. If you want the form input to be handled by the server you need to use CGI (Common Gateway Interface). This allows you to process the form input automatically. The server might for example build up a database from the input received by some customers. Another example are index-pages like Yahoo. They usually have a form for making a search in their database. The user gets a response quickly after the submit button was hit. He does not have to wait until the people maintaining

this server read the input and then look up the information requested. This is done
automatically by the server. JavaScript cannot do things like this. You cannot create guestbooks with JavaScript because JavaScript isn’t able to write to a file on the server. You can only do this through CGI. Of course you can create a guestbook with the people answering via e-mail. You have to enter the feedback manually though. This is ok if you don’t expect to get 1000 feedback mails a day.

This script here is plain HTML. So no JavaScript is needed here! Only, of course, if you want to check the input before the form is submitted you will need JavaScript. I have to add that the mailto-command does not work everywhere.

<form method=post  action="mailto:your.address@goes.here"  enctype="text/plain">
      
Do you like this page?
<input name="choice" type="radio"  value="1">Not at all.<br>
<input name="choice" type="radio"  value="2" CHECKED>Waste of time.<br>
<input name="choice" type="radio" value="3">Worst  site of the Net.<br>
<input name="submit" type="submit"  value="Send">
</form>

 

The property enctype="text/plain" is used in order to send plain text without encoded parts. This makes it much easier to read the mail.

If you want to validate the form before it is sent over the net you can use the onSubmit eventhandler. You have to put this event-handler into the <form> tag. This looks like this:

function validate() {
// check if input ok
// ...
if (inputOK) return true
else return false;
}
...
<form ... onSubmit="return validate()"> ...

With this code the form isn’t being sent over the Internet if the form input was wrong.
Setting the focus to a certain form-element With the help of the focus() method you can make your form a little bit more user-friendly. You can define which element is in focus at the beginning. Or you could tell the browser to focus on the form where the input was wrong. This means that the browser will set the cursor into the specified form-element so the user does not have to click on the form before entering anything.

You can do this with the following piece of script:

function setfocus() {
document.first.text1.focus();
}

This script would set the focus to the first text-element in the script I have shown above. You have to specify the name of the whole form - which is called first here - and the name of the single form element - here text1. If you want to put the focus on this element when the page is being loaded you can add an onLoad-property to your <body> tag. This looks like this:

<body onLoad="setfocus()">
We can extend this with the following code:
function setfocus() { document.first.text1.focus(); document.first.text1.select(); }

The text-element gets the focus and the text contained in this text-element is being selected.








}