Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

Further Programming - Part IV

• Validating forms

• Submitting form input

• How to set the focus to a certain element

Form input is very important for some Web- pages. The form input is often sent back to the server again. JavaScript has got the functionality
to validate the form input before sending it to the server. First I want to show you how forms can be validated. Then we will have a look at
the possibilties for sending information back with JavaScript or HTML.
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. You can enter anything into the form elements and then push the button. Also try to enter
nothing and then push the button.

Top of Form
Enter your name:

Enter your e-mail address:

Bottom of Form
Concerning the first input element you will receive an error message when not entering anything. 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 '17' you will get 'Hi 17!'.
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>
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. You have learned about it
in part 6 of this introduction.
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 @.

What different possibilities do exist for submitting the contents of a form? The easiest way is to submit the form input via e-mail. This is the
method we are going to look at a little closer. If you want to get feedback without e-mail and want the server to handle the input
automatically you have to use CGI at the moment. You would need CGI for example if you wanted to make a search engine like Yahoo- where
the user gets a result quickly after the form input. 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 does not have the functionality to do things like this.
Even if you want to create a guestbook you can't make the server to add the information automatically to an existing HTML- page with
JavaScript. Only CGI can do this at the moment. 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 for every browser- but the newer browsers support it.

<FORM METHOD=POST ACTION="mailto:your_email@goes.here">


<H3>Do you like this page?</H3>
<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>
You will get the feedback through e-mail by doing this. The only problem is that you will receive a mail that might seem very cryptic at the
first glance. Sometimes all spaces are filled up with '+' and sometimes they are filled up with '%20'. So+this+might+look+like+this. There
are some parser programms out on the Net, I believe, which will put the received mail in to a nicer format.

There is another nice thing so you can make your form elements 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 user- input was done 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();
return;
}
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 here called first - 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 for example:

<body onLoad="setfocus()">
/////////////////////////////////////////////////////
Disabling a Radio Button
Question: How do I disable a radio button in a form (making it not selectable)?

Answer: To make a radio button not selectable, in the button's INPUT tag you can use an onClick event handler like this:
<INPUT type="radio" name="myButton" value="theValue"
onClick="this.checked=false;
alert('Sorry, this option is not available!')">
In the example below, the "Courier delivery" option is disabled. Try it now - you'll get an alert box with the text Sorry, this option is not
available!
Top of Form
Delivery method (choose one):

download

regular mail

courier delivery

////////////////////////////

Validating a Form
Question: How do I validate the form input before sending it to the server?

onSubmit event handler. When the user submits the


Answer: To validate the form input, call your validation function from the form's
onSubmit event handler. The form will actually be submitted to the server only if the handler
form, the browser will first invoke the
returns true. In the following example, the onSubmit event handler validates the user's email address. (For simplicity, the address is
considered to be valid if it does not contain spaces, contains the @ character and if @ is neither the first nor the last character.)
Top of Form

Submit

Your email:
Bottom of Form
This example used the following code:
<script language="JavaScript">
<!--
function isValid() {
var email=document.form1.t1.value;
if (email.indexOf(' ')==-1
&& 0<email.indexOf('@')
&& email.indexOf('@')+1 < email.length
) return true;
else alert ('Invalid email address!')
return false;
}
//-->
</script>

<form name=form1
action="javascript:alert('The form is submitted.')"
onSubmit="return isValid()">
Your email:
<input type=text name=t1 size=20 >
<input type=submit value=Submit>
</form>
Bottom of Form

Combining Input Fields


Question: Can I save space in my form by getting more than one input value from just one text field?
Answer: Yes. For example, you can display a text input field and a select box. Using the select box, the user will be able to choose which
kind of value to input in the text field. All input data can actually be submitted to the server in additional hidden form elements. Try this
example:

Top of Form

Your name: Enter!

Bottom of Form
This form was created using the following JavaScript code:
<form name=form1 action="" onSubmit="return validate()">
<input name="name" type=hidden value="">
<input name="email" type=hidden value="">
<input name="country" type=hidden value="">
<select name=s1 onChange="refill()">
<option value="name" selected >Your name:
<option value="email" >Your email address:
<option value="country" >Your country:
</select>
<input name=t1 type=text value="" size=20>
<input name=b1 type=submit value="Enter!">
</form>

<script language="JavaScript">
<!--
isFilled=new Array(0,0,0);
oldActiveField="name"; oldIndex=0;
theActiveField="name"; theIndex=0;
theValue='';
theForm=document.form1;

function refill() {
oldIndex=theIndex;
theIndex=theForm.s1.selectedIndex;
oldActiveField=theActiveField;
theActiveField=theForm.s1.options[theIndex].value;
theValue=theForm.t1.value;
eval('theForm.'+oldActiveField+'.value=theValue');
eval('theForm.t1.value=theForm.'+theActiveField+'.value');
if (theValue!='') isFilled[oldIndex]=1;
if (theValue=='') isFilled[oldIndex]=0;
}

function read() {
oldIndex=theForm.s1.selectedIndex;
oldActiveField=theForm.s1.options[oldIndex].value;
theValue=theForm.t1.value;
eval('theForm.'+oldActiveField+'.value=theValue');
if (theValue!='') isFilled[theIndex]=1;
if (theValue=='') isFilled[theIndex]=0;
}

function validate() {
read();
for (var k=0; k<isFilled.length; k++) {
if (!isFilled[k]) {
theIndex=k;
theForm.s1.selectedIndex=k;
theForm.t1.value='';
theActiveField=theForm.s1.options[k].value;
if (oldIndex==k) alert ('Please fill in your '+theActiveField)
return false;
}
}
alert ('You are submitting the following data:'
+'\nName: '+theForm.name.value
+'\nEmail: '+theForm.email.value
+'\nCountry: '+theForm.country.value
)

return false;
// Instead of returning false in all cases,
// a real-life code here would validate the data
// and return true if the user submitted valid data
}

//-->
</script>

You might also like