javascript html forms
javascript html forms

if-then-else

In our daily life we frequently come across conditional work. For example, suppose you make a guard stand at the entrance of some hall and tell him to ask every trespasser his name. “If the name is ‘Ali’, let him enter; else deny entrance.” Re-read the last sentence. It is one of the best examples of conditional constructs. In programming, too, we come across conditional code. For example, you ask the visitor to your site his name. If the name is ‘Ali’, let him visit; else deny entrance. Although not a working code, following snippet will make the syntax clear. Remember, the equality in JavaScript is checked with “==” rather than a single equal sign.
if (name == "Ali")
{
// do something
}
else
{
// do something else
}
Note a few things: the conditional construct starts with an if keyword. Then comes the condition part enclosed between brackets. Here we are checking for equality. That is why, the equal sign == has been used. We can check for a lot of other things in an if condition. You will see that part later. Next, there is some code enclosed between curly brackets. This code will be executed if the condition name == “Ali” is satisfied. Otherwise, the code following the keyword else will be executed. I think that’s enough for now. We will see a working code example, but first let’s review some HTML from tags.

HTML Forms – A Review

If you have visited a site or two, you might have the experience of filling in a form on the Web. It may be a login userid and password or some registration form. These types of forms can be created with plain HTML. Here, I will provide a brief review of HTML tags related to form creation. If you have no previous experience of creating forms, please visit some HTML tutorial site. I will recommend http://www.htmlgoodies.com. First of all, a form is enclosed between <form> and </form>. Inside we can declare various form elements, like text boxes; selection drop down list; clickable buttons; and check boxes; etc. Following is an example of a simple form that accepts the visitors name and email.
<html>
<head>
</head>
<body>
<form name="myForm">
Name   <input type="text" name="userName" size="30">
<br>
Email   <input type="text" name="userEmail" size="30">
<br><br>
<input type="button" value="Click here!">
</form>
</body>
</html>

Some Explanation

HTML is so simple that most of the things are self explanatory. I will only give you a brief explanation here. The text boxes are created by a type = “text” attribute, while clickable button by type = “button” attribute. In addition to this, we also give a name to almost every form element. In the last example, the names given to the two text boxes are userName and userEmail respectively. You can choose any name you like. We have already seen that an onClick event occurs when somebody clicks a button. We will make use of one other event onSubmit in our discussion. Let’s now combine HTML forms with if conditions to do form processing. But first, you need to know how to pass values to functions.

Passing Values to Functions

Sometimes you want to send a value (some text or some number) to a JavaScript function. Suppose, for example, you want to display user id entered by the visitor with an alert() box. This means that there will be a JavaScript function to display the alert() box. But the contents of the box will be determined at run time (i.e. when the function will be called). Different visitors will have different user ids. The only possible way of displaying the user id entered by the visitor is by passing it to your JavaScript function. Moreover, the function must know that it has to receive some value. A form object (we know what objects are, right?) will be received like this.
<script language="JavaScript">
function functionName (aForm)
{
// do processing on aForm
}
</script>

Example 1 – Processing HTML Forms

Finally, the example we were all waiting for! We will make a simple HTML form. It will contain only one field – userid. Next, we will send the form to a JavaScript function, which will in turn tell the userid sent to you. The only thing that needs explanation is the expression aForm.userid.value. It simply means the value of the userid text box of the form (read from right to left). Pretty simple?
<html>

<head>
<script language="JavaScript">
<!-- Hiding from old browsers
function displayId (aForm)
{
myId = "Your user id is " + aForm.userid.value;
alert (myId);
}
// done hiding -->
</script>
</head>
<body>
<form name="myForm">
Enter your userid   <input type="text" name="userid" size="30">
<br>
<input type="button" value="Click here!" onClick="displayId(myForm)">
</form>
</body>
</html>

Text Boxes

Text Boxes are used to get input in text form, like userid and addressing information, etc. In JavaScript a text box object supports several properties; the most important of which is “value”. Suppose you have a text box named email which contains the text [email protected]. You can access this text (or value) by using email.value in a JavaScript function. This value property is a string in itself and therefore supports all string properties like length and methods like toUpperCase(). Suppose you want to determine the length of the email address entered by the user; you can do so by writing email.value.length. Following example will clarify the things.
<html>
<head>
<title>HTML Form Processing</title>
<script languague="JavaScript">
<!--hiding from old broswers
function check_form (myForm)
{
len = myForm.email.value.length;
alert ("Your email address is " + len + " characters long");
}
// -->
</script>
</head>
<body>
<form name="survey">
Enter you email <input type="text" name="email">
<input type="button" value="Check Size" onClick="check_form(survey)">
</form>

</body>
</html>

Code Explanation

I will stop here for a moment to take a look on the above JavaScript code. We are gradually coming to complex scripts, right? Here, in this example, we have created an HTML form as apparent from the body section of the HTML page. This form has been given the name of survey. You may choose a name of your liking. Anyhow, the form contains two elements: a text box to accept user’s email address and a button to check the address’ size. When the button is clicked it simply calls the check_form() function defined in the head part of the page. Note that we have passed the current form named survey to this function. The JavaScript function in turn receives the form. Inside this function, it will be referred to as myForm. So, we assign len the length of the email address by specifying myForm.email.value.length, i.e. read from right to left to get: the length of the value of the email object in myForm.

Passwords? In HTML?

Yes, HTML allows you to accept passwords. You may have entered your password on certain web sites (like Hotmail, Yahoo! Mail, etc.). The passwords appear as asterisks on these pages. You can create the same effect by using input type=”password” in your form. The password type is similar to text type in all other respects, except that it is hidden under asterisks. Following is a code that is similar to the above one. It tells the length of your password and instructs the user to enter a password if the length is zero (Remember the if statements?).
<html>
<head>
<title>HTML Form Processing Example 2</title>
<script languague="JavaScript">
<!--hiding from old broswers
function check_form (myForm)
{
len = myForm.pass.value.length;
if (len == 0) alert ("Please enter a password!");
else alert ("Your password is " + len + " characters long");
}
// -->
</script>
</head>
<body>
<form name="survey">
Enter you password <input type="password" name="pass">
<input type="button" value="Get Size" onClick="check_form(survey)">
</form>

</body>
</html>

Radio Buttons

Radio Buttons are used to select one option from a relatively short list. The only important property associated with a radio button is checked, which tells whether a radio button is selected or not. Following is an HTML code that displays three options for selection and displays a message when the button below them is clicked.
<html>
<head>
<title>HTML Form Processing</title>
<script language="JavaScript">
<!-- Hiding from old browsers
function check_form (form)
{
alert ("You clicked the button");
}
// -->
</script >
</head>
<body>
<form name="survey">
How did you come to know about this site:<br>
<input type="radio" name="refer" value="search"> Search Engine<br>
<input type="radio" name="refer" value="magazine"> Some Magazine<br>
<input type="radio" name="refer"> value="surf"; Just surfed in!<br>
<br> <input type="button" name="submit" value="submit"
onClick="check_form(survey)"> </form> </body> </html>

Code Explanation

Note a few things about the above code: First of all, the input type of the radio buttons is radio. Secondly, all of them have the same name. That makes sense because they are all part of the same question. These radio buttons differ only in their value attribute. Now try this: Copy, paste, save and then load this script into your browser and click the submit button without selecting any option. The alert message will still appear! Now, how can you confirm a selection has been made before submitting this form. To comprehend the answer we need to know two things. The first one we will cover is arrays. We will briefly touch them. A more detailed discussion is deferred for some later article.

Array of Radio Buttons

An array, simply put, is a collection of objects referred to by their position in the collection. In the example given above, we have a collection of radio buttons named “refer”, or in programming terms: an array “refer” of radio buttons. The value at the first position in an array is supposed to be 0. So, the search option is refer[0]. Similarly, the magazine option is refer[1] and the surf option is refer[1]. We can now re-write the check_form function to tell us the value of the option selected. The new function can also inform us if we click the button without selecting anything.
function check_form (form)
{
selection = false;
for (i=0; i<form.refer.length; i++)
if (form.refer[i].checked == true)
{
selection = true;
alert ("You selected " + i + " number option");
}

if (selection = false)
alert ("You did not select anything");
}

Code Explanation 2

This is a tough code, I know that. Please take your time to grasp it. I provide you some hints. First of all, we set selection variable to false. Once we have done that, we use a for loop to check the “checked” property of every object in the refer array. If any of the item in the refer array has a checked property as true, we display a message that the ith item is selected. At the same time, the selection variable is set to true. After the loop is finished (all the items in the refer array done), we check whether the selection is true. Pay close attention to this: “The selection was set to false in the beginning. It’s value is changed only when the condition in the loop is true (i.e., some option is selected). So, if nothing is selected, the selection variable will be false (otherwise true). Thus, we can check the value of this variable and display a message if nothing is selected.”