Notes 15
— print (last updated: Jul 15, 2009) print

Select font size:

HTML Form Components

HTML Forms are used widely on the Internet to gather information from users or adminstrators accessing the web site. This information is typically entered into a database and later retrieved in other applications. Input for information such as a name, a choices of preferences, etc. are pervasive features. Whenever you type something into an HTML web page and submit the page, it is done through an HTML form.

The HTML Form is constructed using a form element, typically like this:
<form action="a-web-server-side-script">
... form components ...
</form>

As suggested, the information entered is usually processed by a server-side program, i.e., a program running on the server where you accessed the HTML page. In contrast, JavaScript is a client-side program, namely, it runs in the browser.

The components within forms are these:
  1. buttons: used to submit the form or execute JavaScript code.
  2. textfields and password fields: single line inputs
  3. check boxes and radio buttons: allow the user to say yes/no to a choice, or one of several choices. radio buttons can be used to give an exclusive choice among several possibile options
  4. selection lists: these give a choice through a popup or scroll list
  5. textareas: multi-line inputs
Our purpose is not to use these components within a form for server-side processing of the information, instead we simply want to use them for collecting and displaying information with JavaScript by manipulating the DOM (Document Object Model) properties of the elements.

Buttons

Buttons can be created using the input element with type attribute either submit, reset or button but we prefer to use the actual button element because it is simpler to create the button's label. When the button is used, you have to define the onclick mouse event attribute to make the button do something.
 <button onclick="">Push Me</button>

The input elements

The input element represents many diverse HTML form elements including buttons, text fields, checkboxes, etc. The type of element depends on the type attribute which is one of these values:
text, password,
checkbox, radio,
submit, reset, button (types of buttons),
file, hidden, image,
The other attributes used in input elements are these:

Textfields and Password fields

The most important attributes are size and value:
  1. <input type="text" size="20" />
    
  2. <input type="text" size="20" value="YOUR NAME" />
    
  3. <input type="password" size="20"/>
    

Checkboxes and radio buttons

These are input elements of type checkbox or radio. They allow the user to check something, typically using the mouse. The important attributes are name and checked. The checked attribute is a boolean attribute. In order to be activated it only has to be listed among the attributes and otherwise has no particular value.
  1. <input type="checkbox" /> 
    Would you like to receive our monthly newsletter?
    
    Would you like to receive our monthly newsletter?
  2. <input type="checkbox" checked /> 
    Would you like to receive our monthly newsletter?
    
    Would you like to receive our monthly newsletter?
Radio Buttons create exclusive choices by using the name attribute, which is required for the radio button to function. Two or more radio buttons with the same value of the name attribute (within the same form) have mutually exclusive choices.
  1.  <input type="radio" name="gender1" /> Male 
     <input type="radio" name="gender1" /> Female
    
    Male Female
  2.  <input type="radio" name="gender2" checked /> Male 
     <input type="radio" name="gender2" /> Female
    
    Male Female

Selection Lists

Selection lists are created by the select element. They can appear as drop-down lists or scrolled lists of items. Each item in the list is specified by an option element and has a has a visible label and an underlying value. If the value is absent, it is taken to be the label.

In addition to the name attribute the key attributes are these:
  1. <select>
     <option value="1">dog</option>
     <option value="2">cat</option>
     <option value="3">cow</option>
     <option value="4">pig</option>
    </select>
    
  2. <select size="3">
     <option value="1">dog</option>
     <option value="2">cat</option>
     <option value="3">cow</option>
     <option value="4">pig</option>
    </select>
    

Textareas

The textarea element is used for permitting multi-line input. The key attributes are
rows: number of rows
cols: number of columns
The other attributes used are similar to those for textfields:
name, readonly, tabindex, accesskey
  1. <textarea rows="5" cols="20"></textarea>
    
  2. <textarea rows="5" cols="20">With some 
    initial input</textarea>
    

Using onclick and window.location

Form elements are commonly processed when the user clicks a button. In the case of a button element it activates a JavaScript function specified by the onclick event. Here is the simplest example of this behavior, activating the alert function:
<button onclick="alert('button pressed')">Press Me</button>
which behaves like this:

Button as hyperlink

We can also make a button act like a hyperlink. The key idea is to use the JavaScript location object and reset the it to the target URL as follows:
<button onclick="location='http://www.google.com'">Go to Google</button>
Here is the effect:
Strictly speaking, we are using the JavaScript object
window.location
which indicates the current URL displayed by the browser.

Image as hyperlink

We can also make an image act like a hyperlink without surrounding it by anchor elements. Combining the onclick event with the onmouseover/onmouseout rollover effects used in Notes 13 we get this:
<img src="yahoo_out.gif"
     onclick="location='http://www.yahoo.com'" 
     onmouseover="src='yahoo_over.gif'" 
     onmouseout="src='yahoo_out.gif'" />
with the following effect:

Text as hyperlink

We can make simple text, surronded by a span act like a hyperlink. One missing ingredient is how to make the cursor behave differently. We can do so by setting the cursor style property as in this style rule:
span.link {
  color: blue;
  text-decoration: none;
  cursor: pointer;  /* make mouse not look like "text cursor" */
}

Consider this usage:
Here is a 
<a href="http://www.google.com">real hyperlink to google</a>
as others in this document.
<br /><br />
Here is a 
<span class="link"
 onclick="location='http://www.google.com'"
 onmouseover="style.color='red';style.textDecoration='underline';window.status='http://www.google.com';"
 onmouseout="style.color='blue';style.textDecoration='none';window.status=''"
>manufactured hyperlink to google</span> 
using a span element.
The effect is this:
Here is a real hyperlink to google as others in this document.

Here is a manufactured hyperlink to google using a span element.

Limitations of JavaScript hyperlinks

We control the appearance of the status bar at the bottom of the browser. The ability to do so is often not permitted by default in browsers, such as Firefox 3.

In general, you should probably prefer hyperlinks to such JavaScript-driven elements since hyperlinks will work under all circumstances, whereas JavaScript usage can be limited or turned off completely.

Using textfields for I/O

We are interested in providing a textfield (i.e., input type text) for user input and allowing the value within that textfield (i.e., the value attribute) to be read and/or written by JavaScript code. In particular, if we start with a textfield:
<input type="text" id="someid" />
then within JavaScript, we can access the value within the textfield:
var someid = document.getElementById("someid")
and use it for reading or writing as in these examples:
var str = someid.value  // read contents of textfield
or
someid.value = 33       // write 33 into the textfield

The square program revisited once more

A further improvement to the squaring program from Notes 12 is to allow the input to be obtained from an HTML textfield, without having to rely on the prompt function dialog.
Square operation via textfields
As you see, both input and output use textfields. The output textfield uses the boolean attribute readonly (see the Boolean Attributes section below) which disallows user input, ensuring that only JavaScript can set the value. Here is the code:
<html>
<head>
<title>Square in Textfields</title>
<script type="text/javascript">
<!--
function square() 
{ 
  var source = document.getElementById("source")  // source textfield
  var output = document.getElementById("output")  // output textfield
  var str = source.value        // source value
  var num = parseFloat(str)     // string -> numeric
  if (isNaN(num)) {
    alert( "invalid entry" )
    output.value = ""
  } else {
    var result = num * num      // compute result
    output.value = result
  }
}
// -->
</script>
</head>

<body>
Input: <input type="text" id="source"/>
<button onclick="square()" >Square It</button>
<p>
Output: <input type="text" id="output" readonly />
</p>
</body>
</html>

Selection List Example

In JavaScript, a selection list's value is the value of the selected object, or null, if nothing is selected. The thing to keep in mind is that the id attribute is defined in the select element, not in the options. In particular, if we start with a selection list:
<select id="someid" > 
 <option value="value1">option1</option>
 <option value="value2">option2</option>
 ...
</select>
then within JavaScript, we can access the selected option's value:
var someid = document.getElementById("someid");

var selected_value = someid.value // someid.value is the selected value

Example: Go to selected site

The following selection list give a choice of sites to go to:
Go to site
Here is the code:
<html>
<head>
<title>Select and Go</title>
<script type="text/javascript">
<!--
function gotosite() 
{ 
  var site = document.getElementById("site")
  location = site.value                      // go to this site
}
// -->
</script>
</head>

<body>

Choose a search engine:
<select id="site">
  <option value="http://www.google.com">Google</option>
  <option value="http://www.yahoo.com">Yahoo</option>
  <option value="http://www.dogpile.com">DogPile</option>
</select>
<button onclick="gotosite()">Go to site</button>
</body>
</html>

A key idea expressed in this example is the usage of the JavaScript object

window.location
which dictates the current URL displayed by the browser. This property can be reassigned to a new URL as we have done in this program, causing the browser to relocate to this site.
location = site.value;

Using the onchange attribute

An interesting variation of this selection-list navigation is allowing the location to change when it is selected without having to press a button. The idea is to use the JavaScript onchange attribute which is activated from the selection list itself whenever a new item is chosen. Here is the example:
Goto site on change
Here is the code:
<html>
<head>
<title>Select and Go on change</title>
<script type="text/javascript">
<!--
function gotosite() 
{ 
  var site = document.getElementById("site")
  if (site.value != "NONE") { 
    location = site.value         // go to this site
  }
}
// -->
</script>
</head>

<body>

Choose a search engine:
<select id="site" onchange="gotosite()">
  <option value="NONE">-----</option>
  <option value="http://www.google.com">Google</option>
  <option value="http://www.yahoo.com">Yahoo</option>
  <option value="http://www.dogpile.com">DogPile</option>
</select>
</body>
</html>

Observe the alterations we've made. In particular, you need to add a "no site" option, as the first selection, in this case:
<option value="NONE">-----</option>
If we change to a real site, and go back, we'll see our site chose still selected. Therefore, if we then change to the "no site" choice with value NONE, we must recognize this fact and omit the location reassignment in the gotosite function:
if (site.value != "NONE") 
  location = site.value; // go to this site

Boolean Attributes

A boolean attribute of an HTML element is one which has no associated values; its effect occurs mearly by its presence. These are used primarily in HTML form component elements. In certain cases, it is possible to set these attributes in JavaScript, in which case the boolean constants true and false are used. For example, if we have a button with id="myelt", then we can can disable/enable it dynamically as follows:
var myelt = document.getElementById( "myelt" )

myelt.disabled = true   // disable it, or
myelt.disabled = false  // enable it
The following is a simple demo program illustrating the usage of boolean attributes:
Boolean Attribute Demo
Here is the code:
<html>
<head>
<title>Boolean Attribute Demo</title>
<script>
function init() {
   var cb = document.getElementById("cb")
   var bt = document.getElementById("bt")
   
   cb.checked = true
   bt.disabled = true
}

window.onload = init

</script>
</head>
<body>
<h2>Boolean Attribute Demo</h2>

<input type="checkbox" id="cb" />

<button type="" onclick="alert('pressed')" id="bt">Button</button>

<input type="text" id="tf" value="some content" readonly />

<select>
<option value="a">A</option>
<option value="b" selected >B</option>
</select>

</body>
</html>

Checkbox and Radio Button Examples

For checkboxes and radio buttons the checked attribute corresponds to the JavaScript property of the same name. This is a boolean value, i.e. true or false.

In particular, if, say we have a checkbox:
<input type="checkbox" id="someid" />
then, we can test whether this is checked or not in JavaScript:
var someid = document.getElementById("someid");
if (someid.checked) {
  // do something based on the box being checked
}
Here are some examples which illustrates the point.

Check Test

This example illustrates how radio buttons/checkboxes can be both activated and tested.
Check Test
Here is the code:
<html>
<head>
<title>Check Test</title>
<script type="text/javascript">
<!--
function check_test()
{
  var c = document.getElementById("c")
  var r1 = document.getElementById("r1")
  var r2 = document.getElementById("r2")

  var cinfo = document.getElementById("cinfo")
  var r1info = document.getElementById("r1info")
  var r2info = document.getElementById("r2info")

  if (c.checked) 
    cinfo.innerHTML = "yes" 
  else 
    cinfo.innerHTML = "no"

  if (r1.checked) 
    r1info.innerHTML = "yes" 
  else 
    r1info.innerHTML = "no"

  if (r2.checked) 
    r2info.innerHTML = "yes" 
  else 
    r2info.innerHTML = "no"
}
// -->
</script>
</head>
 
<body>
<input type="checkbox" id="c" onclick="check_test()" /> Checkbox
<br />
<input type="radio" name="rb" id="r1" onclick="check_test()" /> Button 1
<input type="radio" name="rb" id="r2" onclick="check_test()" /> Button 2

<p>
Checkbox checked: <span id="cinfo">no</span>
<br />
Button1 checked:  <span id="r1info">no</span>
<br />
Button2 checked:  <span id="r2info">no</span>
</p>

</body>
</html>

A hoagie with extras

This example illustrates checkbox usage:
Hoagie with Extras
Here is the code:
<html>
<head>
<title>Hoagie with Extras</title>
<script type="text/javascript">
<!--
function test()
{
  var output = document.getElementById( "output" )
  var m = document.getElementById( "m" )
  var c = document.getElementById( "c" )
  var p = document.getElementById( "p" )
  var t = document.getElementById( "t" )
  
  var cost = 4.95;   // base cost
  if (m.checked) cost = cost + .71
  if (c.checked) cost = cost + .50
  if (p.checked) cost = cost + .22
  if (t.checked) cost = cost + .16
 
  output.innerHTML = "Please pay the server: $" + cost
}
// -->
</script>
</head>
 
<body>
Order a hoagie:<br />
<input type="checkbox" id="m" /> extra meat ?<br />
<input type="checkbox" id="c" /> extra cheese ?<br />
<input type="checkbox" id="p" /> extra pickles ?<br />
<input type="checkbox" id="t" /> extra tomatoes ?<br />
<button onclick="test()">Calculate Cost</button>

<p id="output"></p>

</body>
</html>

Tax calculator

A radio button is used for exclusive choices. Keep in mind that you must use name attribute with the same value. This is simple example of usage:
Tax Calculator
Here is the code:
<html>
<head>
<title>Tax Calculator</title>
<script type="text/javascript">
<!--
function compute()
{
  var sal = document.getElementById( "sal" )

  var sgl = document.getElementById( "sgl" )
  var mfj = document.getElementById( "mfj" )
  var mfs = document.getElementById( "mfs" )

  var tax = document.getElementById( "tax" )
 
  var num = parseFloat(sal.value)

  tax.innerHTML = ""    // clear it initially
 	
  if (isNaN(num)) 
    alert( "Invalid Input" )
  else {
    var result

    if (sgl.checked) 
      result = num * .12
    else if (mfs.checked) 
      result = num * .14
    else if (mfj.checked) 
      result = num * .23

    result = Math.round( 100 * result ) / 100
    tax.innerHTML = result
  }
}
// -->
</script>
</head>
 
<body>
 
Salary: <input type="text" id="sal" />

<p>
<input type="radio" name="status" id="sgl" checked /> Single
<br />
<input type="radio" name="status" id="mfs" /> Married filing separately
<br />
<input type="radio" name="status" id="mfj" /> Married filing jointly
</p>

<button onclick="compute()">Compute Tax</button>

<p>
Tax due: <span id="tax"></span>
</p>

</body>
</html>


© Robert M. Kline