HTML Events and Forms
HTML Forms
Although the JavaScript prompt() function that we have been using is a quick way to ask the user to input a single value, it isn't convenient for multiple values.
When you test a program in the JavaScript Test Area, you do not have any other way to get values from the user.
However if the program is part of an HTML document, you can use a form to get user input.
Intro to HTML Forms
- Forms let you provide input.
- An HTML form application has two parts to it
- First, the visible part that you see on the page
- It displays inputs that are called form controls or form fields (informally, "widgets").
- It can also include text and images.
- Second, a program or script that processes the data from the form.
- The program may be on the server (called server-side or back-end)
- It may also be Javascript that is included with the document (called client-side or front-end)
- Without the program, nothing happens.
- When a visitor uses a form page
- First the browser gets the source code and displays the form on the page (just like other HTML documents)
- The user fills in the fields
- The browser packages up the data and sends it off to the back-end application.
- The application receives the data and processes it.
- The application provides a response to the server.
- The server sends the response back to the browser, which displays it to the user.
The form element (tag)
- The form element is a container
<form>....</form> - The form element contains the form control elements
- It can also contain text, images, paragraphs, heading, and most block elements.
- the form element may NOT contain another form element.
HTML Markup
<!DOCTYPE html> <html> <head> <title>Mailing List Signup</title> <meta charset="utf-8"> </head> <body> <h1>Mailing List Signup</h1> <form action="/mailinglist.php" method="post"> <fieldset> <legend>Join our email list</legend> <p>Get news about the band such as tour dates and special MP3 releases sent to your own in-box.</p> <ol> <li><label for="firstlast">Name:</label> <input type="text" name="username" id="firstlast"></li> <li><label for="email">Email:</label> <input type="text" name="email" id="email"></li> </ol> <input type="submit" value="Submit"> </fieldset> </form> </body> </html> |
Mailing List Signup |
Important form attributes
- The form element has two essential attributes
action
- The action attribute's value specifies the application that will process the form
- It is often the URL of a program
- The action attribute is required
- the action value may be empty (""), but the attribute must be present.
method
- The method attribute specifies how the information is sent to the server
- The method information is part of the HTTP protocol
- There are two possible values: GET and POST
- Method GET sends the encoded data as part of the URL.
For example, if I use self-servide to search for CS 201 in spring, 2014, the request URL ishttps://selfservice.hood.edu/SelfService/Search/SectionSearch.aspx?sort=CourseId&eventid=CS+201&year=2014&term=SPRING&num=10
- Method POST sends the encoded data as a separate attachment to the request.
- GET is like sending a postcard, with the address and message (the data) both visible.
- POST is like sending a package, with the address label visible on the outside and the contents (the data) hidden inside.
- GET is the default - it is used if you do not explicitly specify POST
Form controls
There are several different types of form controls. Now we will look at a few of them:
- text inputs, often called textboxes.
- push buttons
Many form controls are created using the same basic tag, the input tag, with different types
Its basic form is
<input name="name for the control" type="specific type" value="optional initial value" >
Different types may have additional attributes, such as size or maxlength.
Buttons
If the type of the input
is "button", graphical browsers will display a raised button labeled with the value.
In the example, the displayed button is shown immediately below the tag.
<input type="button" name="push" value="I'm a button" >
Nothing happens when you click this example button, because we haven't yet told it what to do.
You add an action to a button with an event handler.
Example
Here's an example of a button with JavaScript to handle the click event on it. The event value is the same as the one in the first example.
<input type="button" name="Greet" value="Click me" onclick=" alert('Hi'); " >
Submit and reset buttons
<input type="submit">:
<input type="reset">:
- The submit button initiates the form processing, packaging up the data and sending it to the action.
- The reset button restores the form control elements to their initial values
- They don't need a name attribute, because they aren't for data entry.
- You can provide a value - it will be used to label the button
Example
HTML Markup
<label>First Name <input type="text" name="firstname" ></label><br> <label>Last Name <input type="text" name="lastname" ></label> <p> <input type="submit"> <input type="reset" value="Start over"> </p> |
|
Textbox (single-line text) inputs
If the type of the input is "text", graphical browsers will display a one-line input box with the value shown in it. Non-graphical browsers will present the text input differently.
Example
<input type="text" name="entry" value="Hi. Type in me." >
Specialized single-line inputs
Naming Conventions
Before we continue, we will establish some guidelines for naming forms, buttons, and text inputs to help distinguish them from JavaScript variables when we refer to them. Following a consistent pattern of naming makes programs easier to read and debug.
The technique we will use is to begin the name with a three-letter abbreviation indicating the type of the object. It is distinguished from the rest of the name by beginning the rest with a capital letter or by using an underscore.
- form names should begin with frm
- button names should begin with btn
- text input names should begin with txt
For instance, using this convention, the names in the examples above would be
btnPush
orbtn_push
txtEntry
ortxt_box1
A sample form might be named frmSample
or frm_sample
From now on, all the examples will follow this convention. You should also use it in your labs and homework. It is commonly called Hungarian notation because it is a variation of a convention originated by Charles Simonyi, a programmer of Hungarian origin.
<input type="button" name="btnGreet" value="Click!" onclick=" alert('Hi!') " >
Referring to form controls from within JavaScript
To refer to form controls in a form, you use their names.
Form input elements such as buttons and text inputs must be inside a form to be recognized by name. If they are not, you will get errors that they are not defined. The form must also have a name.
To refer to another control in the form, and you must use its complete name in the following format:
document.form_name.control_name
Example
In the following example, the first button reports its own value. The second button tells the value of the first button. Notice how the name of the form is used.
<form name="frmExample1" action=""> <input type="button" name="btnFoo" value="See me" onclick="alert('This button name: ' + this.name + '. This button value: ' + this.value);" > <input type="button" name="btnGoo" value="See the other" onclick="alert('Other button Name: ' + document.frmExample1.btnFoo.name + '. Other button value: ' + document.frmExample1.btnFoo.value );" > </form>
Example 6 in a complete page. Look at the source code to see the details. The second button gives some additional output as well as the value.
Notice that you can have line breaks inside the event handler if you don't want the long line to wrap around, just as in normal JavaScript, but you must be very careful about where you place the breaks. Do not break the line inside a JavaScript quoted string.
Using numeric values in programs
The text input box values are used in programs the same way you use the values returned by the JavaScript prompt
function.
We already used them when displaying names and values in an alert box. They can also be used in computations.
Because the text input box values are text, we must use parseFloat
before they are used in numeric computations.
Example: Using values from a text input
For example, suppose a web page has a form named frmRectangle with two text input boxes named "txtLength" and "txtWidth".
A button event handler could use the values to find the area:
you type numbers in the two text input boxes.
When you click the button, it multiplies the two values.
<form name="frmRectangle" action=""> Enter length: <input type="text" name="txtLength" value="" > Enter width: <input type="text" name="txtWidth" value="" > <input type="button" name="btnDoArea" value="Find the area" onclick=" alert('Area is: ' + parseFloat(document.frmRectangle.txtLength.value) * parseFloat(document.frmRectangle.txtWidth.value) ); " > </form>
Example 7 as a complete separate page.
Warning
Remember, always use parseFloat
with a text input value that is to be treated as a number.
The textarea
(Multi-line text input) form control element
The text input box is limited to a single line of text. There is no way to show multiple lines inside a text input box.
There is another form control called a textarea that can show multiple lines. The textarea element is a container, with opening and closing tags. It should have a name. In this course, we will begin the name with ara.
The value of a textarea is not an attribute inside the tag. It is the text in the container, between the starting and ending tags.
<textarea name="name of textarea"> The text initially displayed in the textarea is here, between the starting and ending tags. </textarea>
If there is more text than can be shown in the visible box area, graphical browsers will add a scrollbar. Most will also wrap the lines of text within the area.
Example 8 - A textarea
<textarea name="araComments_1"> This is the text that will initially be displayed in the textarea. It has line breaks in it, and is long enough to be wider than the textarea. </textarea>
Modifying the displayed size of a textarea.
The dimensions of a textarea can be changed by using rows
and cols
(for columns) attributes.
rows
specifies the height in terms of lines of text.cols
specifies the width in terms of number of characters.
Example - textarea with rows
and cols
attributes.
<textarea name="araComments_2" rows="5" cols="40"> The text initially displayed in the textarea is here, between the tags. Notice the blank line before this one. And the spacing between words in this sentence. Whitespace inside a textarea container is reproduced exactly. </textarea>
Angle brackets (tags) inside a textarea
Text displayed in a textarea is plain text, like that displayed in an alert box.
HTML tags in the output will be displayed verbatim.
To see an example, try executing alert("<em>Hello.</em>") in the JavaScript test area.
Example - tags inside a textarea.
<textarea name="araComments_3" rows="3" cols="60"> <em>Text area</em> <br/>Notice that the tags appear verbatim in the display. They are not "processed" iby the browser. </textarea>
Example 10 as a complete page.
Creating line breaks with JavaScript
As we saw in earlier examples, if the original text in the HTML source code is written with line breaks, they will be included in the textarea.
Long lines will usually be wrapped at the end of the display area.
In a JavaScript string, you have to use the combination "\n"
to make a line break in the displayed value.
It is called the newline character - it creates a line break in plain text.
The combination is called an escaped character.
Demonstration
As an example, test each of the following statements in the JavaScript test area.
document.write("This \n is \n a \n break?"); alert("This \n is \n a \n break?");
Summary: To make line breaks in displayed output using JavaScript:
- use
"<br>"
tags indocument.write
output - use
"\n"
inalert
- use
"\n"
in values assigned to atextarea
Appending additional text to a textarea
When you assign a new value to a textarea (or text input box, or button, or variable), the new value completely replaces the old one.
Sometimes you want to append the new text - add it to what is already there, not replace it.
To accomplish this, use the concatenation operator:
value = value + added amount
Example - Appending a value to a textarea.
<form name="frmExample8" action=""> <textarea name="araComments" rows="4" cols="80"> This is the text that will initially be displayed in the textarea. </textarea> <br/> <input type="button" value="Click to add 'MORE'" onclick=" document.frmExample8.araComments.value= document.frmExample8.araComments.value + 'MORE'; " > </form>
Here is Example 11 as a complete page..
Example
As an example, let's work through an extended version of the carpet area calculation.
The problem
Suppose you are working at a carpet store. The carpet comes in 2 meter wide rolls and is sold by the linear meter at $23.95 per meter. To help customers plan ahead, you want to create a web page for them. The customer should be able enter the length and width of a room (in meters) and find its area (in square meters), the number of linear meters that must be purchased, and the cost.
Analysis
There are three steps to the calculations:
- first, find the area (length times width)
- then find the number of linear meters to purchase. There are 2 square meters of carpet per linear meter on the roll, so the amount to buy will be the area divided by 2.
- finally, calculate the cost as linear meters * 23.95
So our computations will be
area is length * width; linear_meters is area / 2; cost is linear_m * 23.95
Design
The length and width will need to be entered in text input boxes. The other amounts are all calculated.
A very basic outline is:
- get room width (make a variable to store it)
- get length (make a variable to store it)
- compute area as length * width (make a variable to store it)
- display area
- compute linear meters to purchase as area / 2 (make a variable to store it)
- display linear amount
- compute cost as linear amount * 23.95 (make a variable to store it)
- display cost
There will need to be a textarea for displaying the result.
Implementation
The form will be named frmCarpet, the textareas for length and width will be named txtLong and txtWide, and the textarea for output will be named araDisplay.
This is the event handler.
//JavaScript program to calculate carpet purchases // 1. Get length - it should be a number, so use parseFloat var carp_long = parseFloat(document.frmCarpet.txtLong.value); // 2. Get width - it should be a number, so use parseFloat var carp_wide = parseFloat(document.frmCarpet.txtWide.value); // 3. Compute area var area = carp_long * carp_wide; // 4. Compute linear amount var linear_m = area / 2; // 5. Compute cost var cost = linear_m * 23.95; //6. Display area, amount to purchase, and cost // The \n creates a line break. document.frmCarpet.araDisplay.value = 'Your room is ' + carp_long + ' by '+ carp_wide + ' meters.\n' + 'It will require '+ area + ' square meters of carpet.\n' + 'You should purchase ' + linear_m + ' linear meters at a cost of $' + cost + '.';
Here is The example page.
Test
Test it with the following dimensions. Make note of the results.
- 3 by 4 m
- 3.5 by 4.5 m
- 8 by 5 m
- 11 by 7 m
Example continued
Modify the carpet calculator so the the user can enter several room sizes. Each time a calculation is requested, the line of results should appended to the textarea so the previous ones are still visible.
We will use spaces in the lines of text to approximate columns. (This doesn't work very well, but we don't have a better way.) The headings on the output wil be provided as the initial textarea value
<textarea name="araDisplay" rows="4" cols="60"> Length Width Area Lin_amount Cost </textarea>
The calculations do not need to be changed. Each new set of results is appended to the previous textarea value instead of replacing it.
document.frmCarpet.araDisplay.value = document.frmCarpet.araDisplay.value + carp_long + '\t' + carp_wide + '\t'+ area + '\t' + linear_m + '\t\t$' + cost + '\n' ;
The computational steps of the JavaScript programs are not changed. Only the way the resutes are displayed is different.
Here is a link to the page with the modified example. Be sure to look at the source code to see the details.
Make choices (previously, lesson 17)
All programming languages provide the ability to execute a sequence of instructions based upon a decision.
This change in the order of execution is called a branch.
In JavaScript, the branching is accomplished using the if
statement.
Example : A guessing game
Before we discuss the if
statement in detail, let's look at an example.
In this example, we will look at a program that simulates a simple guessing game.
The user is to enter a guess between 1 and 10.
The program then sees if the user's guess is correct.
For the purposes of this program, we'll assume that the magic number is 4.
If the guess is correct, then an appropriate message is displayed.
Notice that the comparison uses the symbol ==
, not just =
(which is reserved for assignment).
I am thinking of a number between 1 and 10. Can you read my mind?
The button's onclick event uses an event handler to check the guess:
1 //check the guess 2 3 var user_guess = document.frm_example1.txt_guess.value; user_guess = parseFloat(user_guess); 4 //compare to secret number 5 if (user_guess == 4) 6 { 7 alert('Congratulations! Your guess is correct!'); 8 } 9 alert('Thanks for playing.');
What this says is: if the value of the variable user_guess is identical to 4, then display the alert "Congratulations! Your guess is correct!"
If the user guesses incorrectly, that is, if the expression user_guess == 4 is false, then lines 6 through 8 are skipped.
But in either case, line 9 is executed, always printing out "Thanks for playing!".
Here is the example as a complete page.
Using strings in conditions
What if we want the user to guess a word instead of a number? Strings can be used in conditions too.
With a string, the == means "is identical to".
Example : Guessing a word
var user_guess = document.frm_example2.txt_guess.value;
//compare to 'secret' word
if ( user_guess == 'Cat' )
{
alert('Right! I was thinking of Cat!');
}
alert('Thanks for playing.');
The event handler is very similar to the first example.
However there is no parseFloat() because we are using the value as a string.
Here is the example as a complete page.
Experiment by entering "cat" or "Cat " (with an extra space).
Notice that the you must enter "Cat" with the correct capitalization to be correct.
Boolean Expressions
The simplest if
statement has the format:
if (Boolean_expression) { // Body of If-Then statement goes here between curly braces }
The condition is the expression that is being tested; it is enclosed in parentheses.
The body of the if statement is a block of statements enclosed in curly braces.
The statements in the body of the if-then should be indented to make it easier to see where the body begins and ends.
The condition is always a Boolean expression - an expression that evaluates to either true or false.
In an if
statement, the Boolean expression inside the parentheses is evaluated to see if it is true or false.
If the expression is true, then the body of the statement is executed.
If it is false, the flow of control skips to the statement immediately after the closing curly brace.
Relational operators
Operators, such as ==
, that compare values are called relational operators. Here is a list of relational operators:
JavaScript Notation | Meaning |
---|---|
== | equal to |
!= | not equal to |
> | greater than |
>= | greater than or equal to |
< | less than |
<= | less than or equal to |
Relational operators with strings
When used to compare strings, the order used by <, <=, >, and >= is lexicographic order - similar to dictionary order.
In lexicographic order, case makes a difference; uppercase letters are "smaller" than lowercase ones.
Example
Test the following in the JavaScript tester area.
Notice that you can have more than one statement inside the {}.
if (2 <= 3) { document.write('2 is smaller'); alert('On to the next one...'); } document.write('<br > .... <br >'); if ('abc' <= 'abd') { document.write('abc comes before abd'); alert('Second one done. Moving on...'); } document.write('<br > .... <br >'); if ('a' <= 'Z') { document.write('a comes before Z'); alert('That was the last.'); } document.write('<br > .... <br >'); document.write('done');
Nested if
statements
The body of an if
statement can contain another if
statement.
Notice how the complete inner if statement (in green and italic) fits between the braces of the outer (red) one.
// Using a nested if
var user_guess = parseFloat(document.frm_example6.txt_guess.value);
if (user_guess >=1 )
{
if (10 >= user_guess)
{
document.frm_example6.ara_message.value=
'Close. At least you are between 1 and 10.';
}
}
Nesting the if
statements makes the program test for both conditions being true. The inner condition is checked only after the outer one is known to be true.
if-else
Branching frequently involves alternatives. In the last lesson, we simply wrote several separate if
statements to cover different alternative cases.
The alternatives can be expressed more clearly by adding an else
or elseif
to the if
statement.
The if-else
statement is an expansion of the If-Then statement. The general format of an if-else
statement looks like:
if (Boolean_expression) { // Body of if statement goes here } else { // Body of alternative else statement goes here. }
Be sure to notice the placement of the curly braces.
If the Boolean expression evaluates to true, then the body of the if statement is executed.
Otherwise, if the Boolean expression is found to be false, then the body of the else statement is executed.
Example - Guessing game revisited
I am thinking of a number between 1 and 10. Can you read my mind?
The complete example page also changes the image - and puts back the original image when you click the reset button. Look at the example's soure code to see how it is done.
Program development
Double-check your spelling
When referring to form controls in your program, the names you use must be EXACTLY the same as the names of the form controls.
The JavaScript interpreter does not understand what they mean.
For example, txtWidget and txt_widget or frmPizza and frmpizza are NOT the same to the interpreter even though a human many not notice the difference.
If an error message says something is undefined, it often means you have mistyped a name.
Variables must be typed exactly the same every time - cost and Cost are different.
Close what you open
Tags and symbols that come in pairs must be complete.
In your JavaScript, check that you have correctly closed
- quotes
- parentheses
- braces
- and brackets
The W3C validator will help catch HTML errors.
The validator will not help with errors within JavaScript.
Indent
Use indentation to make your HTML and JavaScript structure more visible.
It makes it easier to see if you closed things properly.
Take advantage of syntax highlighting
Crimson Editor, and other good programming editors, will color-code keywords and parts of code, and indicate paired brackets.
This isn't just to make it look pretty!
THe color helps you see if you accidentally used a reserved term as a variable name, or neglected to close a quote.
To get JavaScript highlighting, your program must be in a file with the .js extension.
If you are writing an event handler, as the examples, your file has a .html extension.
One strategy is to write the program in a separate file to get the syntax highlighting and then copy and paste it into the onclick-" " space.
Use the Error Console
Use the Error Console
Use the Error Console
Guidelines
- Use the document type XHTML 1.0 Transitional when your page contains a form.
- Provide an
action=""
attribute in the opening form tag to ensure stardards compliance. - Use the Hungarian notation convention for namimg your forms and form controls.
- Use single quotes inside the JavaScript of an event handler attribute and double quotes around the entire handler value.