\n"); } else { header("Content-type: text/html; charset=utf-8"); } ?> Assignment 7

Introduction

This is an optional assignment. If you do it, you can receive credit for doing an extra homework assignment, but you can get full credit for the homework portion of your course grade (10 to 15% of your course grade) even if you do not do this assignment. Aside from the possibility of receiving a little bit of extra credit towards your course grade, a reason for working on the assignment is that doing so should help you prepare for the JavaScript questions on the final exam.

There will be a final exam study guide that will give you an idea of what material will be on the final exam. I will write that web page after I finish this one.

For this assignment, you are to use JavaScript to prevent the user from submitting the form you constructed for Assignment 6 if the user has not entered any information for certain fields on the form. This page will basically give the code to you; the process of typing it in yourself as you read the description presented here should give you a fairly good understanding of some important features of working with JavaScript code.

Project Description

  1. Set up the project.

    Create a project directory named Assignment_07, and copy everything from Assignment 6 into that directory. If you didn’t create a separate css directory for that assignment, this means just copying over the index.xhtml file. Create a scripts directory, either under Assignment_07, or directly under My Website; this is where your JavaScript program for this assignment will go.

    Test your web page at this point to make sure it still works the same as it did when it was Assignment 6. There is no need to create a new stylesheet for this assignment; just make sure that the index page still is linked to either the original assignment_06.css stylesheet, or to a copy of it.

    Create a JavaScript file and save it in your scripts directory with the name assignment_07.js. You can create this file from Dreamweaver’s New menu, which will give you an empty file except for a one-line comment at the beginning that says, “JavaScript Document”. I suggest changing that comment to match the name of the file, “assignment_07.js”.

    Enter the following code into your script file:

    function init() { alert("Assignment 7"); } window.onload = init;

    Link the script file to your web page by adding the following script tag to the index page. This tag may go either in the head of the page, typically after the links to the page’s stylesheet(s), or at the end of the page, just before the closing /body tag. The latter placement is not as logical as the former, but (a) both positions work because processing a script tag has no effect on the appearance of a page, and (b) most browsers interrupt their rendering of a page when they encounter a script tag while they send a request for the page to the server, wait for it to come back, and then process the code in it. By putting the tag near the end of the page, you get browsers that follow this procedure to render the page before reading the script file, making the page load time seem shorter to the user. By the time the user does something that requires the script to have been processed, the browser will have had time to retrieve and process the script file.

    Test the web page: when it loads, a pop-up that says “Assignment 7” should appear. Pop-ups are annoying, so replace the alert() statement with the following one:

    console.log("Assignment 7");

    This statement will work only in Firefox, and only if you have the Firebug extension installed. If you try to view the page using Internet Explorer or Opera, you will get a “script error” on the page, and your JavaScript code will not work. Safari simply ignores the call to console.log(). To see the message, you have to open the Firebug console window. The easiest way to do this is just to press the F-12 key, but you can also use the Firefox Tools menu to do it. If Firebug is disabled (evidenced by F-12 not doing anything, you will definitely have to use the Tools menu to start Firebug the first time. There are several tabs in the Firebug window; if the Console tab is selected you should see the message from the console.log() statement.

    From now on, this page will assume you have Firebug’s console tab visible so you can see messages produced by calls to console.log(). As mentioned above, pop-ups are annoying (you have to click on each one in order to proceed with your work), so use Firebug’s console.log() instead of JavaScript’s built-in alert() function while developing your code. Just be sure to remove the calls to console.log() before releasing your code to the public so they won’t cause problems for non-Firebug users.

    Notice the indentation structure of the JavaScript code. Like XHTML, JavaScript (and other programming languages) typically involve lots of nesting of blocks within blocks. Instead of XHTML tags, JavaScript enclosed blocks inside curly braces ( { … } ). If you line up matching braces vertically and indent the code inside them, it makes it easier to spot mis-matches. Some code editors will highlight matching braces as you type them; in Dreamweaver, you can highlight all the code between a matching pair of braces, parentheses, or square brackets by positioning the cursor inside them and using the Edit->Balance Braces menu item.

  2. Set up a submit event handler.

    An event handler is any JavaScript that is set up to run whenever an event occurs. You have already seen an event handler: the init() function is set up to run when the window.onload event occurs. That is, when the browser finishes getting all the web page’s files from the server and has built the DOM tree, the data structure that holds the information about all the XHTML elements for the page, including each element’s tag name, attributes, style information, and contents.

    For this assignment, the task is create a function that verifies that the user has filled in the form properly. (The definition of “properly, ” for now, will be whether they have typed anything into the textarea element or not.) Here is code that finds the form element in the DOM tree, and connects an event handler to the submit event that is triggered when the user clicks on the form’s submit button:

    function submitHandler() { console.log("Submit event detected."); return false; } function init() { var allForms = document.getElementsByTagName('form'); var theForm = allForms[0]; theForm.onsubmit = submitHandler; } window.onload = init;

    JavaScript functions do not have to return a value, but they may. For event handlers, returning a value of false prevents the default behavior for that event from occurring. In the case of a submit event, the default behavior is to submit the form to the web page that will process the form data, so returning false from this submitHandler() function prevents the form from being submitted. (The script needs to tell the user what happened; that comes later.)

    The last line of the init() function (which is the page’s (“window’s”) load event handler) sets up submitHandler() as the submit event handler for the form. The first two lines get a reference to the page’s form tag from the DOM tree for the page.

    The document object is a reference to the root of the DOM tree; it is created automatically by the browser when it processes the contents of a web page. The function getElementsByTagName() searches the DOM tree for all form elements, and returns an array containing references to all of them, even if there are none. The web page you constructed for Assignment 6, we know, has exactly one form element, and the second statement uses a subscript with the value 0 to get the first element from the array returned by the previous statement and to put it in theForm. (Array subscripts always start at 0 in JavaScript, so allForms[0] gets the first element of the array. Since we know there is exactly one form on this particular web page, the first element of the array is actually the only element in this particular array.)

    The variables allForms and theForm are not actually necessary; I put them there to make the code clearer (I hope). The entire init() function could have been written equivalently like this:

    function init() { document.getElementsByTagName('form')[0].onsubmit = submitHandler; }

    Often, having fewer lines of code to read makes a program easier to understand. For beginners it generally just makes it too complex.

  3. Make submitting the form conditional.

    Right now, the form never gets submitted. The next step is to find out whether the user has typed anything into the textarea or not. The following code uses an if-else statement to see whether the user has typed anything into the textarea or not:

    function submitHandler() { var allTextareas = document.getElementsByTagName('textarea'); var theTextarea = allTextAreas[0]; var theText = theTextarea.value; if (theText === '') { return false; } else { return true; } }

    The triple-equal operator ( === ) tests whether two things are the same or not. If they are the same, the value of the expression is true and the code inside the first pair of curly braces gets executed. If they are not the same, the value of the expression is false, and the code inside the curly braces following the else gets executed instead.

    You will see the double-equal operator ( == ) used in a lot of JavaScript programs, but you should avoid using it because it automatically converts the two operands to be the same type if possible, leading the program to treat two things as the same when they are not. For example, '3' == 3 is true even though one side is a string and the other side is a number; The string gets treated like a number because it looks like one. But '3' === 3 is false strings are not the same thing as numbers even if they look like them.

  4. Give the user feedback when the form is not submitted.

    Clicking on the submit button and having nothing happen is bad user interface design. The simplest solution is simply to put an alert() call into the event handler:

    if (theText === '') { alert("You idiot!"); alert("You didn't type anything in the textarea!!"); alert("Form data submission blocked!!!"); return false; } else { return true; }

    While the above example might be a bit extreme, it does illustrate some things to avoid in designing a web page: alert boxes in general; multiple alert boxes where one would suffice; using jargon the user probably does not understand (“textarea” and “form data submission”); insulting the user; and emotion or excitement for something mundane.

    Rather, you can use JavaScript to display an informative error message or provide simple feedback to indicate something is wrong. As an easy example, here is how to make the background of the textarea turn red if the user tries to submit the form without typing anything in it:

    // Make sure the textarea is not empty if (theText === '') { theTextarea.style.backgroundColor = "#fcc"; return false; } else { theTextarea.style.backgroundColor = "#fff"; return true; }

  5. Other improvements.

    The project as developed so far should give you a good sense of how you can use JavaScript to verify that a use filled a form out properly before submitting the form to the script that will process the form data. Note that if the user has JavaScript disabled, the form data will always be submitted without any verification, which means that the data processing script always has to verify the data it receives and not rely on JavaScript to have taken care of this anyway. All the JavaScript is doing is giving the user better and quicker feedback than would have happened if the server-side script did all the work.

    An easy way to make the form better is to indicate what parts of the form are required, for example by putting a red asterisk (* or ) next to them. (The second one is a “low asterisk”, which you can get with the ∗ character entity.)

    Using JavaScript to display an error message on the web page is not all that hard, but it is beyond the scope of this assignment page. But we can add another event handler so the red background goes away once the user has typed a few characters into the textarea. That involves setting up a third event handler, one that is activated every time the user types a character in the textarea:

    if (theText === '') { theTextarea.onkeyup = keyupHandler; theTextarea.style.backgroundColor = '#fcc'; return false; } else …

    And the keyup event handler could look like this:

    function keyupHandler() { var theText = document.getElementsByTagName('textarea')[0].value; if (theText.count > 3) { theText.style.backgroundColor = '#fff'; } else { theText.style.backgroundColor = '#fcc'; } }

    If the user types more than three characters into the textarea, the handler changes the background color back to white. Until then (or if the user types in more than three characters and backspaces so there are again fewer than three still there) the background color stays (or goes back to) red.

    There is a working version the form for this web page below. If you experiment with it, you will see that there is a way you can submit the form even if you type in only 1-2 characters. See if you can figure out how to do that, and then see if you can fix it so the user always has to type in more than three characters.

Submit the Assignment

Check your assignment in the usual ways: test its behavior, validate the xhtml and css, and do a case-sensitive link check. When you sumbit it use CS-081 Assignment 7 as the subject line of your email message. You can get the extra credit for doing the assignment only if you submit it by midnight of the due date, December 19.