Forms and Events-I in Java Script

In the last two articles, we took a look at some of the aspects of the Browser Object Model (BOM). The different elements of BOM are in fact a super set of at least seventy per cent of all web development activities, which a web developer does. A good understanding of other aspects, or to be more precise, knowledge of objects of the BOM models is essential in your career as web developer.

In the series Revenge of JavaScript, which (the title) I must confess is a lot dramatic, we are using ubiquitous JavaScript tool to hack the BOM.

We had a brief look into various objects under the BOM and we have already written a script to identify the various browsers, and operating systems that a web site visitor uses. Now, let us take a look at the form object, and the form element. These are ideas that are fundamental to our study on scripting with JavaScript!

The form is a lot more complex object than the navigator, or document object. Again like the navigator object, the implementation of ideas of forms has been affected by the politics of browser wars. It is easier to look at the form object as a container object, which, in turn, contains several properties and methods.

Some examples of form elements are input, select, textarea, checkbox, and so on.

As mentioned in an earlier article, you can access a form by indexing it either with a number, or by it's name. You can in fact access a property, or method by indexing the form. Check couple of examples:

document.forms[0].action
document.forms["justcheck].action

An HTML form is defined by using the <form/> tag. Some of the attributes of this tag include

method -- This indicates whether the browser should send a GET, or POST request. We will discuss GET, and POST in detail later.

action -- This indicates the URL to which, the form must be submitted.

enctype -- This indicates the way the data must be encoded when sent to the server. The default is application/x-www-url-encoded, but it may be set to multi-part/form-data if the form is uploading data, as is the case of the email attachment program.

accept -- Lists the mime types the server will accept and handle

A form can contain a number of input elements. Here are some examples of such input elements.

1. text box
2. file , a file upload box
3. radio -- A Radio button
4. checkbox
5. password 
6. button
7. submit, a button to submit information
8. reset, a button to reset information entered in the form
9. hidden -- A field that is not rendered on the screen
10. image
11. The selection/option element is elements that either renders a combo box or a list box consisting of values defined by elements
12. textarea-- Renders a multi-line textbox whose lines are determined by rows and columns attributes.

Now, let us write a quick form. The easiest way to hack a form together is to hack one from a web site.

Here is a script, which I hacked from the popular web site, www.code4jobs.com. It is simple, and straightforward.

<html>

<html>

<body>

<form name="form1" method="post" action="register.jsp" >
<br> <br>
<br> <br>

Name: <input name="name" size="30" maxlength="50" value="" type="text">
<br> <br>
E-mail:<input name="email" size="30" maxlength="100" value="" type="text">
<br> <br>

Password:
<input name="password" size="30" maxlength="100" value="" type="password">


<br> <br>

Experience (in yrs)
<input name="years_experience" size="30" maxlength="50" value="" type="text">
<br> <br>

Key Skills <textarea rows="2" name="key_skills" cols="20"></textarea>
<br> <br>
<input name="submit" value="Register" type="submit">
</form>
</body>
<html>

Dissecting the code above, you will notice the following...

For a form to be meaningful, you need to have an action and a method. The action can be a file which can be executed, or even a URL. The method is usually a GET, or POST. Both have their merits, and demerits, and these can be discussed later.

The textarea, as mentioned earlier, is determined by the rows, and columns; and is denoted by rows, and cols. 

The action mentioned is register.jsp, and is a Java Server Page. We will not get into JSP in depth, probably; this script stores information in a database.

As you may have noted, the form is pure HTML, so, let us add a bit of JavaScript, and validate the form.

For the moment let us only validate the email. You need to know regular expressions to understand the complete code. However, the code must be useful--as a web developer, you might have hundreds forms to create, and most forms do have an email field. This code should help you create an email validator.

........................................................................................................................................................................................
<script language="JavaScript">

var results
function checkemail(){
var str=document.form1.email.value
var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
if (filter.test(str))
results=true
else{
alert("Please input a valid email address!")
results=false
}
return (results)
}
</script>


Now you need to add an event onSubmit as given below.

<form name="form1" method="post" onSubmit="return checkemail()" action="javascript:alert('submitted')" >

I have changed the code a bit; I have used a JavaScript command instead of the register.jsp, which will anyways not work, since we have not yet written that JSP program.

One of the perennial problems with Internet is that you sometimes lose connection. As a user, you rarely can figure out whether the connection is on, or not, and many users click on a form more than once. This means double entries, and in some cases, more than two entries of the same information. This is not a pretty sight, when you actually browse through a database table, which has captured multiple entries. 

You can ensure that such double entries are avoided by making this small modification to the above code.

<input name="submit" value="Register" type="submit" onclick ="this.disabled=true;" "this.form.submit()">

Similarly, adding a reset button will reset all the values. Now let us add that in our script.

<input name ="Reset" type ="reset" value ="Reset the Form?">

Another interesting fact is that, you can give initial values to the various fields. For example 

Key Skills <textarea rows="2" name="key_skills" cols="20"> Enter Your key skills viz Python, Perl, Karate</textarea>

Most controls can have their contents accessed, or updated through the value property of the control's object. When used on the right side of an (equal's) assignment, the current value of the object is read. When used on the left side of an assignment, the object is updated. Exceptions to this general rule are:

Check Box
Use the checked property. The value is either true, or false.

Radio Buttons
Use the checked property. The value is either true or false. Since, all radio buttons in a group have the same name, the individual object is accessed via an index. Indexes are numbers in square brackets such as radioButton[0] etc. ( index numbering starts at zero with the first reference in the HTML document.)

Select List
The selected Index property holds the position in the list of the first currently selected item. A value of -1 indicates no selection has been made, or it has been deselected.

form_name.control_name[form_name.control_name.selectedIndex].value reads the value (i.e. what is assigned by the value attribute of the current selection.

form_name.control_name[form_name.control_name.selectedIndex].text reads the text (i.e. what is contained in the option element) of the current selection.

If multiple selections are allowed, you must cycle through the entire select control, testing the selected property of each item in the options array.

File
The file control uses FileUpload.value (note that: the object name is not the same as the type value - this is done to deliberately confuse programmers!)

Events

JavaScript's interaction with different HTML elements happens through events. This is true-- almost of all languages, that events are used to trigger activity. There are a number of events in JavaScript, which we will explore as we get by. The onclick is the simplest example of an event.




A Radio Button example
--------

In this small example, we will learn not only about radio buttons, but also about two important objects in JavaScript.

One is the label, which can be used to tie specific form fields, or in other words, it labels individual form fields. The second is the method getElementById, which is essentially a method that is under the Document Object Model (DOM). This method can be used to tag different elements inside a page.

This small script is useful if you ever make software, and then plan to host it on the net.

................................................................................................................................................................................

<html>
<body>
<form >
<textarea id="textarea" readonly="readonly" rows="8" cols="50">
This license is all nonsense you may agree, or not agree at your risk, and other blah balah 
ablah.</textarea>

<br>
<label for="yes">I have read and accept this agreement</label>
<input id="yes" name="radiobutton" type="radio"/>
<label for="yes">Yes</label>
<input id="no" name="radiobutton" type="radio" checked="checked"/>
<label for="no">No</label>
<input name="act" type="button" value="I agree"
onclick="Agree_software(document.getElementById('yes').checked);"/>
</form>

<script type ="text/javascript">

function Agree_software(entry){
if(entry==true){
alert ("OK, You can now download the software");
}else{
alert("Sorry - You must sign to get the software");
}
}
</script>
</body>
<html>


In the next two articles, we will explore more about forms, and events; and will write some more scripts.




Added on August 11, 2008 Comment

Comments

Post a comment