Lab 3: HTML III, Forms and PHP I

Goals

Learn about...

  1. HTML From Elements
  2. Intro to JavaScript
  3. Connecting Forms to JavaScript functions
  4. Using JavaScript to change a website

Key Concept

HTML has special elements for building input forms to create user interfaces for web applications. Forms can be connected to JavaScript functions to inspect the submitted information and to change the web page dynamically.

Pre-lab

Pre-lab Reading

Pre-lab Activity

Use the following examples to help you answer the Pre-lab Questions in Blackboard.

  1. Text Fields (input tag)
  2. Working text fields with submit button
  3. Password Fields (input tag)
  4. Radio Buttons (input tag)
  5. Working radio button example
  6. Checkboxes (input tag)
  7. Drop-down lists (select and option tags)
  8. Drop-down with pre-selected option (select and option tags)
  9. Text areas (textarea tag)
  10. Buttons (input tag)
  11. Field set and legend (fieldset and legend tags)

In-lab

Remember, if your instructor is busy helping others, raise your hand to make sure the instructor sees that you need help, but then put your hand down and go back to work. As you wait for help, try your best to solve the problem on your own by reading the textbook.

Preparation

  1. For file and folder names only use lowercase letters and never use spaces.
  2. Store all your files in your lab3 folder on the network drive

Part 1a: Validation Form

  1. Open Notepad++
  2. Create a new filed called login.html.
  3. Save the file in your lab3 folder.
  4. Add the required HTML5 page structure:
    <!doctype html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>Login Form</title>
    </head>
    <body>
    
    </body>
    </html>
    
  5. Inside the body, add a label and input text field
    <label for="email">Email</label>
    <input type="text" id="email" ><br>
  6. Below the input text field, add another label and a password field.
    <label for="passwd">Password</label>
    <input type="password" id="passwd"><br>
  7. Key Concept: In the example above, "password" specifies the type of input element, whereas "passwd" is used as the unique identifier so this input element can be connected to the label and so that it can be accessed by JavaScript.
  8. Below the password field, markup the word "Password Again" with a label tag and connect it to a new password field with id = "passwd2".
  9. Finally, add a submit button below the two passwords:
    <input type="button" value="Register" onclick="check()">
  10. Key Concepts:
    • onclick is an HTML attribute the specifies what to do when the button is clicked. Other HTML form elements have attributes that specify what to do when the element is changed or if the mouse hovers over it.
    • In the code above, check() is a call to a JavaScript function that must be defined somewhere.
    • JavaScript functions can be defined directly inside an HTML document by using the script tag. It is a common convention to put script tags inside the head if the code needs to be executed before the page is rendered. If the JavaScript needs to be executed after the page is render, it is a common practice to put JavaScript inside the body immediate before the closing body tag, i.e., </body>.
  11. Cut and the following code and put it inside of a script tag anywhere in the head of your HTML document.
    function check() {
      var email = document.getElementById("email").value;
      var message = "";
      var messageColor = "red";
    
      if (email.search(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/) == -1) {
        message = "Invalid email address";
      }	  	  
      else {
        message = "Valid email and password";
        messageColor = "green";
      }
      showMessage(message, messageColor)
    }
    
    function showMessage(message, messageColor) {
      alert (message + " " + messageColor)
    }  
    
  12. Save your file, open it with Chrome, and test to see if the correct alert message and color appear if you type a valid email address.
  13. Show your instructor that it works and read the key concepts and links below

Key Concepts: The follow explanations and links will help you complete the next part of this activity.

  • document refers to the actual HTML document where the JavaScript code resides.
    Here is the API on the Document Object. Read the first paragraph of the API description.
  • getElementById is a document method that returns an element object. This is why it is so useful to give HTML elements an id name.
  • The value of an input element is the text string that is typed into the element. Thus, document.getElementById("email").value refers to the text string that the user typed into the email text field.
    Here is the API on the Input Element.
  • var is the way to define variables in JavaScript. JavaScript is dynamically typed, which means the type of a variable is determined when you assign it a value. Thus, var email will be a string once we assign it the text string of the "email" element.
  • The .search method can be applied to any string. This method can use a regular expression to search for a pattern in a string. This method returns -1 if a string does not match the regular expression. The very complex regular expression in the code above is used to determine if a string is a valid email address.
    Here is the JavaScript Regular Expression Guide.

Part 1b: Better Validation

Improve the validation script so that it verifies each item below and sets the appropriate error message if the submitted values are not correct:

  • Password must be 6 characters or longer
  • Password must be less than 32 characters
  • Password must include at least one number
  • Password must include at least one letter
  • The two submitted passwords must match

Show your instructor your working script.

Part 1c: Better Error Message

Improve the registration form so that instead of using an alert message box, it displays the error message on the page inside of a color-decorated paragraph. The text should be red if an error message is displayed. The text should be green if the message is "Valid email and password."

Use the following code examples and references to help you:

var myText = document.createTextNode(message);
Create a text node that can be appended inside of an element such as a div or paragraph.
myParagraph = document.createElement("p");
Create a paragraph element that can be inserted or appended anywhere in an actively loaded HTML document.
myParagraph.appendChild(myText);
Appends the text node so that it is "inside" the paragraph.
var myBody = document.getElementsByTagName("body")[0];
Gets all the elements with a certain tag name. Even though there is only one body tag in this document, there could be two or more elements returned by this method. Thus, this method returns an array of elements. Array subscripts, i.e., [], can be used to get the first [0], second [1], or nth [n-1] element.
myBody.appendChild(myParagraph);
Appends a newly created paragraph to the body of the actively loaded HTML document.
myParagraph.id = "error_message";
You can give the newly created paragraph an id name.
myParagraph.setAttribute("style", "color:"+messageColor);
Inserts/sets an attribute. In this case, we set the "style" attribute, which is used to add inline CSS to an element. We could have also set the id using this method, i.e., myParagraph.setAttribute("id", "error_message");

Task: You should append a paragraph to the body of the HTML document. The paragraph should display the correct error message with either red or green text.

Show your instructor your working script.

Part 2: Using EventListener

  1. In Notepad++, create a new HTML file called add.html.
  2. Save the file in your lab3 folder.
  3. Add the following HTML structure; Note that this will not validate as HTML5 because it is missing head, title, and charset. Be sure to add these things. Thus, you will remember them on the exam.
    <!doctype html>
    <html>
    <body>
    
    	<input type="text" id="x"> +
    	<input type="text" id="y"> =
    	<input type="text" id="ans">
    	
    	<script src="add.js"></script>
    
    </body>
    
    </html>
    
  4. In Notepad++, create a new HTML file called add.js.
  5. Save the file in your lab3 folder.
  6. Add the following JavaScript code
    function add() {
    	var x = document.getElementById("x");
    	var y = document.getElementById("y");
    	var ans = document.getElementById("ans");
    	ans.value = x.value + y.value;
    }
    
    var x = document.getElementById("x");
    var y = document.getElementById("y");
    x.addEventListener("change", add, false);
    y.addEventListener("change", add, false);
    
  7. Save the two files and test the add.html application in Chrome

Key Concepts:

  • Rather than use a button with the "onclick" attribute to activate the JavaScript, we use an EventListener to detect when the two input text fields "change" and then we bind this event to a function called add.
  • Rather than embed JavaScript directly in the HTML document, we "link" the JavaScript using the script tag.
  • While this technique appears tedious, it allows a developer to completely separate the HTML and JavaScript code. In the previous example, a JavaScript function call was directly inside an input button (inline JavaScript) and the function definition was directly inside the script tag (embedded JavaScript).

Part 2b: Checkboxes and anonymous functions

Change add.html as follows:

	<input type="checkbox" value="3" id="x"> +
	<input type="checkbox" value="4" id="y"> =
	<input type="text" value="0" id="ans">

Change add.js as follows:

function add(obj) {
	var ans = document.getElementById("ans");
	if (obj.checked)
		ans.value = parseInt(ans.value) + parseInt(obj.value);
	else
		ans.value = parseInt(ans.value) - parseInt(obj.value);
}

var x = document.getElementById("x");
var y = document.getElementById("y");
x.addEventListener("change", function(){add(x)}, false);
y.addEventListener("change", function(){add(y)}, false);

Key Concepts:

  • We have to use getElementById to add an EventListener to elements "x" and "y" and then again to get their values. But, we can just pass the x and y objects into the add function.
  • But, the addEventListener can only accept a function name or definition, not a function call with parameters. However, we can define an anonymous function function() { function call with parameters } that can then make a function call with parameters.
  • Unlike input elements, checkbox elements have a property called "checked" which changes dynamically from true to false depending on if the actual checkbox has been checked or not.
  • Finally, checkboxes can have a value associated with them, which can be set using an HTML attribute or it can be set dynamically using JavaScript.

Part 2c: Select-Option Menus

Using the previous two parts as a model, change the form to replace the two checkboxes with two option-select menus that allow the user to select the values 0 though 9. The input text field should display the sum of the two selected value.