× Introduction Setup Environment Building blocks Built-in functions Data Types Strings Operators Conditional statements Loop statements Functions Arrays Understaing Objects Date Object Number Object Math Object String Object Window Location Navigator History DOM Basics Forms
   Programs
Basic Control Loops Functions Arrays Examples Projects Quick Ref.
   Exercises
Variables Data Types Operators Decision Loops Reeborg's World



Java Script and Forms

In this tutorial you will learn how to read HTML forms and validate an HTML form using JavaScript.

At the heart of the Web is the form. It is used to pass information from the browser to the server. Anytime you go online and order a book, trade at an auction, fill out a survey, or send an e-mail using a Web browser, you are working with a form.

An HTML form offers you a number of ways to accept input, such as radio buttons, check boxes, popup menus, hidden fields, and text boxes; these are called virtual input devices or controls. Once the form has been filled out by a user, it normally is sent to a server where the input is processed by a server-side program, such as a Java servlet, CGI, ASP.NET, or PHP application. It is important to understand how the form data is collected and sent to the server and then what role JavaScript has in this process.

Attributes of the <form>Tag

All forms are in HTML documents. They begin with a <form> tag and its attributes, followed by the input fields where the user enters form information, and end with a </form> tag.
 
<form  name="form1" id="form1" action="URL to server program" method="post">
<input type="text" name="town" id="town">
</form>

The name Attribute. The name is simply a name for the form. You can use forms without giving them names, but you’ll need to assign a name to a form in order to easily use it with JavaScript.

The action Attribute. The action attribute is assigned the URL of the server program that will process the form data.

The method Attribute. A method attribute can be assigned to the

tag. The method attribute indicates how the form data will be sent to the server. Simply put, for pure queries, the GET method is normally used, and for submitting form data, the POST method is used. (The method names are not case sensitive.)

HTML Form Controls

button (name, id): Creates a generic button for user input. It has no default action.

text (name, id, size, maxlength): Creates a textbox for user input. size specifies the size of the textbox. maxlength specifies the maximum number of characters allowed.

textarea (name, id, size,rows, cols) Creates a text area that can take input spanning multiple lines. rows and cols specify the size of the box.

password (name, id, value) Like textbox but input is hidden. Asterisks appear in the box to replace characters typed.

checkbox (name, id, value) Displays a square box that can be checked. Creates name/value pairs from user input. Multiple boxes can be checked.

radio name, id, value Like checkboxes, except only one button (or circle) can be checked.

select (name, id, option, size, multiple) Provides popup menus and scrollable lists. Only one can be selected. Attribute multiple creates a visibly scrollable list.A size of 1 creates a popup menu with only one visible box.

file (name, id) Specifies files to be uploaded to the server. MIME type must be multipart/form-data.

hidden (name, id, value) Provides name/value pair without displaying an object on the screen.

submit (name, id, value )When clicked, executes the form; launches cgi.

image (src, name, id, value, align) Same as submit button, but displays an image instead of text. The image is in a file found at src.

reset (name, id, value) Resets the form to its original position; clears all input fields.

Reading a form value

The document object has a form property. It contains an array of all the forms that have been defined in the document. Each element of the array is a form object and the number in the index of the array represents the order in which the form appeared on the page. The first form would be document.forms[0]. Each form contains elements, also represented as an array.

The elements represent the input types of the form, such as a checkbox, radio button, or text field. By naming each of the forms and its respective elements, it is much easier to work with them in JavaScript.

 
myForm.userName.value

This gives the value of myForm (form), userName (input) element.

 
function displayValue(){
alert("text box value is: " + myForm.userName.value );
};
<form name="myForm">
<input type="text" name="userName" size="50">
<input type="button" value="Show"  onClick="displayValue()" >
</form>

Displaing a form values in new window

 
function display(){
DispWin = window.open('','NewWin','toolbar=no,status=no,width=300,height=200'); 
message = "<ul><li><b>NAME: </b>" + document.form1.yourname.value;
message += "<li><b>ADDRESS: </b>" + document.form1.address.value;
message += "<li><b>PHONE: </b>" + document.form1.phone.value + "</ul>";
DispWin.document.write(message);
}

<form name="form1">
<p><b>Name:</b> <input type="TEXT" size="20" name="yourname">
</p>
<p><b>Address:</b> <input type="TEXT" size="30" name="address">
</p>
<p><b>Phone: </b> <input type="TEXT" size="15" name="phone">
</p>
<p><input type="BUTTON" value="Display" onClick="display();"></p>
</form>

Form Validation

One of JavaScript’s most useful purposes is validating forms. This means using a script to verify that the information entered is valid—for example, that no fields are blank and that the data is in the right format.

You can use JavaScript to validate a form whether it’s submitted by email or to a CGI script, or is simply used by a script.

 
function validate() {
if (document.form1.yourname.value.length < 1) {
alert("Please enter your full name.");
return false;
}
if (document.form1.address.value.length < 3) {
alert("Please enter your address.");
return false;
}
if (document.form1.phone.value.length < 3) {
alert("Please enter your phone number.");
return false;
}
return true;
}

Form and onClick event Handler

function greetme(message){
alert(message);
}
<form>
<input type="button" value="Morning" onClick="greetme('Good morning. This is your wakeup call!')" />
<input type="button" value="Noon" onClick="greetme('Let\'s do lunch.')" />
<input type="button" value="Night" onClick="greetme('Have a pleasant evening.\nSweet dreams...')" />
</form>

Form and onFocus event Handler

function handler(message){
//window.status = message; // Watch the status bar
console.log(message);
//myForm.namestring.value ="red";
//myForm.namestring.style.color ="red";
//myForm.namestring.style.backgroundColor ="red";
}

<input type="text" name="namestring" size="50" 
onFocus="handler('Don\'t forget to enter your name')">

Form and onChange event Handler

function checkValue(){
var grade = document.myForm.grade.value;
 if(grade < 0 || grade > 100){
alert('Please enter a grade between 0 and 100');
}
 else{
confirm('Is '+ grade + ' correct?');
}
}