Chapter 2 lab Chapter 3 lab Chapter 4 lab Chapter 5 lab Chapter 6 lab Chapter 7 lab Chapter 8 lab Chapter 9 lab Chapter 10 lab Chapter 12 lab Chapter 13 lab
Chapter 6 · Lab

Lab 6: JavaScript and HTML Documents

A hands-on DOM lab: form event handlers, accessing elements by name and by id, password verification, checkboxes, radio buttons, text areas and lists, a select menu with onChange, and basic plus email form validation.

Learning outcomes

  • Describe the Document Object Model (DOM) and its hierarchy
  • Use the properties, methods and event handlers of the HTML DOM objects
  • Use HTML DOM event tag attributes to run JavaScript functions
  • Validate form input on the client side before submission

Your progress

Tasks completed 0/6

Log in to save your lab progress. Log in

1

Task 1 — Form event handlers: onClick & onSubmit

HTML tags are represented in JavaScript as objects and tag attributes as properties. Accessing an element's value by its name is the get element by name technique; using getElementById() is the get element by ID technique.

  1. Type a value into each field and click the buttons.
  2. Notice the first form uses onclick, the second uses onsubmit.

Code

events.html
<h1>Form Event Handlers</h1>

<form name="myform1">
  <label>Value x: <input type="text" name="x"></label>
  <input type="button" value="Display X" onclick="DisplayX()">
</form>

<form name="myform2" onsubmit="return DisplayY();">
  <label>Value y: <input type="text" id="y"></label>
  <input type="submit" value="Submit">
</form>
events.js
// Get element by name
function DisplayX() {
  alert(document.myform1.x.value);
}

// Get element by ID
function DisplayY() {
  var thisY = document.getElementById("y");
  alert(thisY.value);
  return false;   // prevent the form from submitting
}

Try it

events.html
events.js
2

Task 2 — Validating form input: passwords

Client-side validation is efficient: the browser does not have to connect to the server, so the user finds out instantly if a field is missing or wrong.

The Verify() function tests whether the two typed passwords are the same. If they differ it shows an error and returns false; if they match it returns true.

  1. Leave both fields empty and submit — see the required-field check.
  2. Type two different passwords and submit.
  3. Type matching passwords.

Code

verify.html
<h1>Password Verification</h1>
<form onsubmit="return Verify();">
  Your password: <input type="password" id="pwd1" name="password"><br><br>
  Verify password: <input type="password" id="pwd2" name="password2"><br><br>
  <input type="submit" value="Check Password">
</form>
<p id="output"></p>
verify.js
function Verify() {
  var pass1 = document.getElementById("pwd1");
  var pass2 = document.getElementById("pwd2");

  if (pass1.value === "") {
    alert("Please enter your password!");
    pass1.focus();
    return false;
  }

  if (pass1.value !== pass2.value) {
    alert("The two passwords you entered are not the same. Please re-enter both now.");
    pass1.focus();
    return false;
  }

  document.getElementById("output").innerHTML = "Passwords match!";
  return false;   // stop the demo form from submitting
}

Try it

verify.html
verify.js
3

Task 3 — Checkboxes, radio buttons, text area & list

Besides text fields, JavaScript can read and write checkboxes, radio buttons, text areas and lists:

  • Use the checked property to test a checkbox.
  • Radio buttons that share a name form an array — loop through them to find the selected one.
  • Use the value property of a text area.
  • Use selectedIndex and options[] for a selection list.

Code

moreformobjects.html
<h1>More Form Objects</h1>
<form name="testform">
  <input type="checkbox" name="check1"> Checkbox 1<br><br>

  <input type="radio" name="rad" value="UM"> Universiti Malaya<br>
  <input type="radio" name="rad" value="UKM"> Universiti Kebangsaan Malaysia<br>
  <input type="radio" name="rad" value="UTeM"> Universiti Teknikal Malaysia Melaka<br><br>

  <textarea name="myarea" cols="40" rows="4">Your text here...</textarea><br><br>

  <select name="list">
    <option value="1">Item 1</option>
    <option value="2">Item 2</option>
    <option value="3">Item 3</option>
  </select><br><br>

  <input type="button" value="Test" onclick="testButton(this.form)">
</form>
<p id="output"></p>
moreformobjects.js
function testButton(form) {
  var messages = [];

  // Checkbox
  if (form.check1.checked) {
    messages.push("You selected the check box.");
  } else {
    messages.push("You didn't select the check box.");
  }

  // Radio buttons (array by shared name)
  var chosen = "";
  for (var i = 0; i < form.rad.length; i++) {
    if (form.rad[i].checked) {
      chosen = form.rad[i].value;
      break;
    }
  }
  messages.push(chosen === "" ? "No university is chosen." : "Chosen: " + chosen);

  // Text area
  messages.push("Text area: " + form.myarea.value);

  // Select list (selectedIndex)
  var item = form.list.selectedIndex;
  messages.push("List selection: " + form.list.options[item].text);

  document.getElementById("output").innerHTML = messages.join("<br>");
}

Try it

moreformobjects.html
moreformobjects.js
4

Task 4 — Select menu with onChange

A select menu can run a function whenever the selection changes, using the onchange event handler. The function receives the select element and reads its value.

In a real page you would navigate to the chosen site with window.location.href = val (shown commented out below).

Code

location.html
<h1>Site Selector</h1>
<form>
  Select a site to browse:
  <select name="SiteSelector" onchange="siteChanged(this)">
    <option value="">-- choose --</option>
    <option value="https://www.utem.edu.my">UTeM</option>
    <option value="https://ftmk.utem.edu.my">FTMK</option>
    <option value="https://ulearn.utem.edu.my">ULearn</option>
  </select>
</form>
<p id="output"></p>
location.js
function siteChanged(select) {
  var val = select.value;

  if (val === "") return;

  document.getElementById("output").innerHTML = "You selected: " + val;

  // In a real page this would navigate the browser:
  // window.location.href = val;
}

Try it

location.html
location.js
5

Task 5 — Basic form validation

Form validation performs two functions:

  • Basic validation — make sure all mandatory fields are filled in.
  • Data format validation — check that the entered data has the correct form and value.

This example validates a name, email, zip code and country. It calls validate() from the form's onsubmit event.

Code

simpleform.html
<h1>Basic Form Validation</h1>
<form action="" name="myForm" onsubmit="return validate();">
  <table cellspacing="2" cellpadding="2" border="0">
    <tr><td align="right">Name:</td><td><input type="text" name="Name"></td></tr>
    <tr><td align="right">Email:</td><td><input type="text" name="EMail"></td></tr>
    <tr><td align="right">Zip:</td><td><input type="text" name="Zip"></td></tr>
    <tr><td align="right">Country:</td><td>
      <select name="Country">
        <option value="">-- choose --</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
      </select>
    </td></tr>
    <tr><td></td><td><input type="submit" value="Submit"></td></tr>
  </table>
</form>
<p id="output"></p>
simpleform.js
function validate() {
  if (document.myForm.Name.value === "") {
    alert("Please provide your name!");
    document.myForm.Name.focus();
    return false;
  }

  if (document.myForm.EMail.value === "") {
    alert("Please provide your Email!");
    document.myForm.EMail.focus();
    return false;
  }

  if (document.myForm.Zip.value === "" ||
      isNaN(document.myForm.Zip.value) ||
      document.myForm.Zip.value.length !== 5) {
    alert("Please provide a zip in the format 12345.");
    document.myForm.Zip.focus();
    return false;
  }

  if (document.myForm.Country.value === "") {
    alert("Please provide your country!");
    return false;
  }

  document.getElementById("output").innerHTML = "All fields are valid!";
  return false;   // stop the demo form from submitting
}

Try it

simpleform.html
simpleform.js
6

Task 6 — Email format validation

An email address must contain at least a @ sign and a dot. The @ must not be the first character, and the last dot must be at least one character after the @.

This function uses indexOf() and lastIndexOf() to find the positions and test them.

Code

emailvalidation.html
<h1>Email Format Validation</h1>
<form name="myForm" onsubmit="return validateEmail();">
  Email: <input type="text" name="EMail" size="30">
  <input type="submit" value="Submit">
</form>
<p id="output"></p>
emailvalidation.js
function validateEmail() {
  var emailID = document.myForm.EMail.value;
  var atpos = emailID.indexOf("@");
  var dotpos = emailID.lastIndexOf(".");

  if (atpos < 1 || (dotpos - atpos < 2)) {
    alert("Please enter a correct email ID");
    document.myForm.EMail.focus();
    return false;
  }

  document.getElementById("output").innerHTML = "Valid email: " + emailID;
  return false;   // stop the demo form from submitting
}

Try it

emailvalidation.html
emailvalidation.js