Appendix A. Answer Key to Exercises

This appendix shows the answers and explanations for the exercises that have appeared throughout the book. In many cases, there is more than one way to solve a problem. Therefore, unless the question specified a particular way to solve the problem, any working implementation is acceptable. It's also expected that your function names will likely differ from the ones in this appendix.

Chapter 1

  1. False. While JavaScript is indeed defined by a standards body, ECMA International, it is not supported on all Web browsers. And the support that does exist varies (sometimes widely) among browsers.

  2. False. There are many reasons why a visitor to your Web site might have JavaScript disabled. The browser they're using might not support it; they might have special software installed that doesn't support it; or they simply might have JavaScript disabled as a personal preference. You should strive to make your site work without JavaScript, or at least have it fail gracefully for those visitors who don't have JavaScript enabled.

  3. A typical JavaScript definition block looks like this:

    <script type = "text/javascript" >
    // JavaScript code goes here
    </script>
  4. False. The version of JavaScript isn't placed within the DOCTYPE definition. In fact, it's quite uncommon to declare the version of JavaScript being used at all.

  5. True. JavaScript code can appear in both the head and the body of a Hypertext Markup Language (HTML) document.

Chapter 2

  1. The code of mysecondpage.htm looks similar to this, though yours may differ slightly:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>My Second Page</title>
    <script type="text/javascript">
    alert("Steve Suehring");
    </script>
    </head>
    <body>
    <p>My Second Page</p>
    </body>
    </html>
  2. Here's the new code, with the changes shown in bold type:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>My Second Page</title>
    <script type="text/javascript">
    function callAlert() {
        alert("Steve Suehring");
    }
    </script>
    </head>
    <body>
    <script type="text/javascript">
    callAlert();
    </script>
    <p>My Second Page</p>
    </body>
    </html>
  3. I created a file called 3.htm and a file called 3.js. Here they are (the reference in 3.htm to 3.js is shown in bold type):

    3.js:

    function callAlert() {
        alert("Steve Suehring");
    }

    3.htm:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>My Second Page</title>
    <script type="text/javascript" src="3.js"> </script>
    </head>
    <body>
    <script type="text/javascript">
    callAlert();
    </script>
    <p>My Second Page</p>
    </body>
    </html>

Chapter 3

  1. The valid statements are a, b, c, and d. The only invalid statement is e, because it uses a reserved word, case, as a variable name.

  2. False. Not all JavaScript statements require a semicolon at the end. In fact, semicolons are usually optional.

  3. The orderTotal variable is changed after the visitor is alerted to how many of an item are ordered, but before the value is returned from the function. The lesson here is that you must be careful not to alter the value or contents of variables unexpectedly. The visitor is expecting to order a certain quantity, but the code clearly changes that quantity after telling the visitor how many he or she ordered!

Chapter 4

  1. Variable declarations:

    var first = 120;
    
    var second = "5150";
    
    var third = "Two Hundred Thirty";
  2. Array:

    var newArray = new Array(10, 20, 30, "first string", "second string");
  3. Escaped string:

    alert("Steve's response was "Cool!"");
  4. Both the first and second variables should convert just fine. The third variable, "Two Hundred Thirty", is reported as NaN (not a number) when passed to the Number() function.

  5. This exercise is for the reader to follow. There is no right or wrong answer.

Chapter 5

  1. Alerts:

    var num1 = 1;
    var num2 = 1;
    var num3 = 19;
    var fourthvar = "84";
    var name1 = "Jakob";
    var name2 = "Edward";
    alert(num1 + num2);
    alert(num3 + fourthvar);
    alert(name1 + name2);
  2. Postfix:

    var theNum = 1;
    alert(theNum);
    alert(theNum++);
    alert(theNum);

    Prefix:

    var theNum = 1;
    alert(theNum);
    alert(++theNum);
    alert(theNum);
  3. Code:

    var num1 = 1;
    var num2 = 1;
    var num3 = 19;
    var fourthvar = "84";
    var name1 = "Jakob";
    var name2 = "Edward";
    alert(typeof num1);
    alert(typeof num2);
    alert(typeof num3);
    alert(typeof fourthvar);
    alert(typeof name1);
    alert(typeof name2);

    This should result in three alerts with the word number followed by three others with the word string.

  4. False. Unary operators appear fairly often in JavaScript, especially within for loops that increment a variable using the ++ postfix operator.

  5. False. While saving a few bytes is helpful, especially for Web applications, it's almost always preferable to spend those same few bytes making the code readable and maintainable.

Chapter 6

  1. Replace YOUR NAME in the following code with the appropriate content:

    var inputName = prompt("Please enter your name:");
    switch(inputName) {
        case "YOUR NAME":
            alert("Welcome " + inputName);
            break;
        case "Steve":
            alert("Go Away");
            break;
        default:
            alert("Please Come Back Later " + inputName);
    }
  2. Here's the code:

    var temp = prompt("Please enter the current temperature");
    if (temp > 100) {
        alert("Please cool down");
    } else if (temp < 20) {
        alert("Better warm up");
    }

    Note that it would also be a good idea to provide a default action in case the temperature is between 20 and 100!

  3. This exercise is actually impossible to accomplish as specified. Because ternary operators expect a single test condition and Exercise 2 required two conditions, a ternary operator cannot be used to accomplish exactly the same task. The following code will create an alert that tells the visitor to cool down if the temperature is above 100 and tells her or him to warm up if the temp is less than or equal to 100:

    var temp = prompt("Please enter the current temperature");
    temp > 100 ? alert("Please cool down") : alert("Better warm up");
  4. Here's the code:

    for (var i = 1; i < 101; i++) {
        if (i == 99) {
            alert("The number is " + i);
        }
    }

    Note that because the variable i began counting at 1 (as was called for in the exercise), the counter needs to go to 101 to meet the requirement of counting from 1 to 100.

  5. Here's the code:

    var i = 1;
    while (i < 101) {
        if (i == 99) {
            alert("The number is " + i);
        }
        i++;
    }

    Note the placement of the postfix increment of the i variable within the loop.

Chapter 7

  1. Here's the code:

    <head>
        <title>Chapter 7 Exercise 1</title>
    <script type = "text/javascript" >
    function incrementNum(theNumber) {
        if (isNaN(theNumber)) {
            alert("Sorry, " + theNumber + " isn't a number.");
            return;
        }
        return theNumber + 1;
    }
    </script>
    </head>
    <body>
    <script type = "text/javascript" >
    alert(incrementNum(3));
    </script>
    </body>
  2. Here's the code:

    function addNums(firstNum,secondNum) {
        if ((isNaN(firstNum)) || (isNaN(secondNum))) {
            alert("Sorry, both arguments must be numbers.");
            return;
        }
        else if (firstNum > secondNum) {
            alert(firstNum + " is greater than " + secondNum);
        }
        else {
            return firstNum + secondNum;
        }
    }
  3. This exercise is meant to show variable scoping problems. Note how the value of the result variable changes outside the function even though the change is made only within the function. The two locations for alerts are shown in bold within the following code:

    function addNumbers() {
        firstNum = 4;
        secondNum = 8;
        result = firstNum + secondNum;
        return result;
    }
    result = 0;
    alert(result);
    sum = addNumbers();
    alert(result);
  4. Here's the code:

    <head>
    <title>Chapter 7 Exercise 4</title>
    <script type="text/javascript">
    var stars = ["Polaris","Aldebaran","Deneb","Vega","Altair","Dubhe","Regulus"];
    var constells = ["Ursa Minor","Taurus","Cygnus","Lyra","Aquila","Ursa Major","Leo"];
    
    function searchStars(star) {
        for (var i = 0; i < stars.length; i++) {
            if (stars[i] == star) {
                return constells[i];
            }
        }
        return star + " Not Found.";
    }
    </script>
    </head>
    <body>
    <script type = "text/javascript" >
    var inputStar = prompt("Enter star name: ");
    alert(searchStars(inputStar));
    </script>
    <p>Stars</p>
    </body>

Chapter 8

  1. Here's the code:

    var star = ["Polaris", "Deneb", "Vega", "Altair"];
    for (var i = 0; i < star.length; i++) {
        alert(star[i]);
    }
  2. Here's one way:

    function Song(artist,length,title) {
        this.artist = artist;
        this.length = length;
        this.title = title;
    }
    
    song1 = new Song("First Artist","3:30","First Song Title");
    song2 = new Song("Second Artist","4:11","Second Song Title");
    song3 = new Song("Third Artist","2:12","Third Song Title");
  3. Assuming the code given in the exercise, this code in the body would concatenate all the names into one long string, as follows:

    var names = new Array;
    for (var propt in star) {
        names += propt;
    }
    alert(names);

    To comma-delimit the names would look like this:

    var names = new Array;
    for (var propt in star) {
        if (names != "") {
            names += "," + propt;
        } else {
            names = propt;
        }
    }
    alert(names);

Chapter 9

  1. Here's the code:

    if (screen.availHeight < 768) {
        alert("Available Height: " + screen.availHeight);
    }
    if (screen.availWidth < 1024) {
        alert("Available Width: " + screen.availWidth);
    }
  2. The full code is shown here, including the code from the step-by-step exercise. The additional code for this exercise is shown in bold. Note the use of the unescape() function to remove the Uniform Resource Locator (URL)–encoded %20 (space) character. This is necessary because the country name "Great Britain" specified in this exercise must be URL-escaped for HTTP GET requests.

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
        <title>Location, Location, Location</title>
        <script type = "text/javascript">
            function showProps() {
                var body = document.getElementsByTagName("body")[0];
                for (var prop in location) {
                    var elem = document.createElement("p");
                    var text = document.createTextNode(prop + ": " + location[prop]);
                    elem.appendChild(text);
                    body.appendChild(elem);
                }
                if (location.search) {
                    var querystring = location.search.substring(1);
                    var splits = querystring.split('&'),
                    for (var i = 0; i < splits.length; i++) {
                        var splitpair = splits[i].split('='),
                        var elem = document.createElement("p");
                        var text = document.createTextNode(splitpair[0] + ": " +
    splitpair[1]);
                        if (splitpair[0] == "country") {
                            switch(unescape(splitpair[1])) {
                                case "Brazil":
                                    alert("Obrigado");
                                    break;
                                case "Great Britain":
                                    alert("Thank You");
                                    break;
                            }
                         }
                         elem.appendChild(text);
                         body.appendChild(elem);
                    }
                }
            }
        </script>
    </head>
    <body onload="showProps()">
    <p>Chapter 9</p>
    </body>
    </html>
  3. This exercise doesn't have an answer in the answer key. The reader can install the User Agent Switcher to complete the exercise.

Chapter 10

  1. Here's the code:

    var newelement = document.createElement("p");
    newelement.setAttribute("id","pelement");
    document.body.appendChild(newelement);
    newelement.appendChild(document.createTextNode("This is a paragraph, albeit a short
    one."));
    var anchorelem = document.createElement("a");
    anchorelem.setAttribute("id","aelement");
    anchorelem.setAttribute("href","http://www.braingia.org/");
    document.body.appendChild(anchorelem);
    anchorelem.appendChild(document.createTextNode("Go To Steve Suehring's Web Site."));
  2. Here's the code:

    var newelement = document.createElement("p");
    newelement.setAttribute("id","pelement");
    document.body.appendChild(newelement);
    newelement.appendChild(document.createTextNode("This is a paragraph, albeit a short
    one."));
    var anchorelem = document.createElement("a");
    anchorelem.setAttribute("id","aelement");
    anchorelem.setAttribute("href","http://www.braingia.org/");
    document.body.appendChild(anchorelem);
    anchorelem.appendChild(document.createTextNode("Click Here"));
    
    var existingp = document.getElementById("pelement");
    existingp.firstChild.nodeValue="This is the new text.";
    var newanchor = document.getElementById("aelement");
    newanchor.setAttribute("href","http://www.microsoft.com/");
  3. Here's the code:

    <head>
    <title>Chapter 10 Exercises</title>
    </script>
    </head>
    <body>
    <div id="thetable"></div>
    <script type = "text/javascript" >
    var table = document.createElement("table");
    table.border = "1";
    var tbody = document.createElement("tbody");
    
    // Append the body to the table
    table.appendChild(tbody);
    var row = document.createElement("tr");
    
    // Create table row
    for (i = 1; i < 3; i++) {
        var row = document.createElement("tr");
        // Create the row/td elements
        for (j = 1; j < 3; j++) {
            // Insert the actual text/data from the XML document.
            var td = document.createElement("td");
            var data = document.createTextNode("Hello - I'm Row " + i + ", Column " + j);
            td.appendChild(data);
            row.appendChild(td);
        }
        tbody.appendChild(row);
    }
    document.getElementById("thetable").appendChild(table);
    </script>
    </body>

Chapter 11

  1. See the section titled Working with Select Boxes in Chapter 11 for an example solution for this exercise.

  2. Based on the pizza.htm example, the <head> portion of code now looks like this, with the additions shown in bold:

    <head>
        <title>Pizza</title>
        <script type = "text/javascript">
    
        function prepza() {
            var checkboxes = document.forms["pizzaform"].toppingcheck.length;
            var crusttype = document.forms["pizzaform"].crust;
            var size = document.forms["pizzaform"].size;
            var crustlength = crusttype.length;
            var sizelength = crusttype.length;
            var newelement = document.createElement("p");
            newelement.setAttribute("id","orderheading");
            document.body.appendChild(newelement);
            newelement.appendChild(document.createTextNode("This pizza will have:"));
    
            for (var c = 0; c < crustlength; c++) {
                if (crusttype[c].checked) {
                      var newelement = document.createElement("p");
                      newelement.setAttribute("id","crustelement" + i);
                      document.body.appendChild(newelement);
                      newelement.appendChild(document.createTextNode(
                          crusttype[c].value + " Crust"));
                }
            }
    
            for (var s = 0; s < sizelength; s++) {
                if (size[s].checked) {
                      var newelement = document.createElement("p");
                      newelement.setAttribute("id","sizeelement" + i);
                      document.body.appendChild(newelement);
                      newelement.appendChild(document.createTextNode(size[s].value + "
    Size"));
                }
            }
    
            for (var i = 0; i < checkboxes; i++) {
                if (document.forms["pizzaform"].toppingcheck[i].checked) {
                      var newelement = document.createElement("p");
                      newelement.setAttribute("id","newelement" + i);
                      document.body.appendChild(newelement);
                      newelement.appendChild(document.createTextNode(
                          document.forms["pizzaform"].toppingcheck[i].value));
                }
            }
        }
        </script>
    </head>

    The HTML looks like this, with the additions again shown in bold:

    <form id="pizzaform-id003" action="#" onsubmit="return false;">
    <table>
    <tr><td>Toppings</td><td>Crust</td><td>Size</td></tr>
    <tr>
    <td><input type="checkbox" id="topping1-id002" value="Sausage" name="toppingcheck"
    />Sausage</td>
    <td><input type="radio" name="crust" value="Regular" checked="checked" id="radio1-id002"
    />Regular</td>
    <td><input type="radio" name="size" value="Small" checked="checked" id="radiosize1"
    />Small</td>
    </tr>
    <tr>
    <td><input type="checkbox" id="topping2-id002" value="Pepperoni" name="toppingcheck"
    />Pepperoni</td>
    <td><input type="radio" name="crust" value="Deep Dish" id="radio2-id002" />Deep Dish</td>
    <td><input type="radio" name="size" value="Medium" id="radiosize2" />Medium</td>
    </tr>
    <tr>
    <td><input type="checkbox" id="topping3-id002" value="Ham" name="toppingcheck" />Ham</td>
    <td><input type="radio" name="crust" value="Thin" id="radio3-id002" />Thin</td>
    <td><input type="radio" name="size" value="Large" id="radiosize3" />Large</td>
    </tr>
    <tr>
    <td><input type="checkbox" id="topping4-id002" value="Green Peppers" name="toppingcheck"
    />Green Peppers</td>
    <td></td>
    </tr>
    <tr>
    <td><input type="checkbox" id="topping5-id002" value="Mushrooms" name="toppingcheck"
    />Mushrooms</td>
    <td></td>
    </tr>
    <tr>
    <td><input type="checkbox" id="topping6-id002" value="Onions" name="toppingcheck" />Onions
    </td>
    <td></td>
    </tr>
    <tr>
    <td><input type="checkbox" id="topping7-id002" value="Pineapple" name="toppingcheck"
    />Pineapple</td>
    <td></td>
    </tr>
    </table>
    <p><input type="submit" id="formsubmit-id002" name="formsubmit" value="Prep Pizza"
    onclick="prepza();" /></p>
    </form>
  3. Add the following code to the <head> portion of the pizza application from the previous exercise:

    function flip(pizzatype) {
        if (pizzatype.value == "Veggie Special") {
            document.getElementById("peppers").checked = "true";
            document.getElementById("onions").checked = "true";
            document.getElementById("mushrooms").checked = "true";
        } else if (pizzatype.value == "Meat Special") {
            document.getElementById("sausage").checked = "true";
            document.getElementById("pepperoni").checked = "true";
            document.getElementById("ham").checked = "true";
        } else if (pizzatype.value == "Hawaiian") {
            document.getElementById("ham").checked = "true";
            document.getElementById("pineapple").checked = "true";
        }
    }

    Use the following HTML form. (Note the addition of three buttons and the change to each ingredient's id attribute.)

    <form id="pizzaform-id004" action="#" onsubmit="return false;">
    <p>
    <input type="button" onclick="flip(veggiespecial)" name="veggiespecial" value="Veggie
    Special" />
    <input type="button" onclick="flip(meatspecial)" name="meatspecial" value="Meat
    Special" />
    <input type="button" onclick="flip(hawaiian)" name="hawaiian" value="Hawaiian" />
    </p>
    <table>
    <tr><td>Toppings</td><td>Crust</td><td>Size</td></tr>
    <tr>
    <td><input type="checkbox" id="sausage" value="Sausage" name="toppingcheck"
    />Sausage</td>
    <td><input type="radio" name="crust" value="Regular" checked="checked" id="radio1-id003"
    />Regular</td>
    <td><input type="radio" name="size" value="Small" checked="checked" id="radiosize1-id001"
    />Small</td>
    </tr>
    <tr>
    <td><input type="checkbox" id="pepperoni" value="Pepperoni" name="toppingcheck"
    />Pepperoni</td>
    <td><input type="radio" name="crust" value="Deep Dish" id="radio2-id003" />Deep Dish</td>
    <td><input type="radio" name="size" value="Medium" id="radiosize2-id001" />Medium</td>
    </tr>
    <tr>
    <td><input type="checkbox" id="ham" value="Ham" name="toppingcheck" />Ham</td>
    <td><input type="radio" name="crust" value="Thin" id="radio3-id003" />Thin</td>
    <td><input type="radio" name="size" value="Large" id="radiosize3-id001" />Large</td>
    </tr>
    <tr>
    <td><input type="checkbox" id="peppers" value="Green Peppers" name="toppingcheck"
    />Green Peppers</td>
    <td></td>
    </tr>
    <tr>
    <td><input type="checkbox" id="mushrooms" value="Mushrooms" name="toppingcheck"
    />Mushrooms</td>
    <td></td>
    </tr>
    <tr>
    <td><input type="checkbox" id="onions" value="Onions" name="toppingcheck" />Onions</
    td>
    <td></td>
    </tr>
    <tr>
    <td><input type="checkbox" id="pineapple" value="Pineapple" name="toppingcheck"
    />Pineapple</td>
    <td></td>
    </tr>
    </table>
    <p><input type="submit" id="formsubmit-id003" name="formsubmit" value="Prep Pizza"
    onclick="prepza();" /></p>
    </form>

Chapter 12

  1. A variation on an example in the chapter:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>Hello Cookie</title>
    <script type = "text/javascript">
    var cookName = "cookie1";
    var cookVal = "testvalue";
    var date = new Date();
    date.setTime(date.getTime()+86400000);
    var expireDate = date.toGMTString();
    var myCookie = cookName + "=" + cookVal + ";expires=" + expireDate;
    document.cookie = myCookie;
    </script>
    </head>
    <body>
    <p>Hello</p>
    </body>
    </html>
  2. Basically the same as Exercise 1, with the changed lines shown in bold:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>Hello Cookie</title>
    <script type = "text/javascript">
    var cookName = "cookie2";
    var cookVal = "testvalue";
    var date = new Date();
    date.setTime(date.getTime()+86400000);
    var expireDate = date.toGMTString();
    var myCookie = cookName + "=" + cookVal + ";expires=" + expireDate + ";secure";
    document.cookie = myCookie;
    </script>
    </head>
    <body>
    <p>Hello</p>
    </body>
    </html>
  3. Unless you're using a Secure Sockets Layer (SSL) connection, you won't be able to read a cookie with the secure flag set.

  4. In Exercise 1, I set a cookie named cookie1; therefore, that's the only one I want to display for this exercise. The code is as follows:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>Reading Cookie</title>
    <script type = "text/javascript">
    var incCookies = document.cookie.split(";");
    for (var c = 0; c < incCookies.length; c++) {
        var splitCookies = incCookies[c].split("=");
        if (splitCookies[0] == "cookie1") {
            alert(incCookies[c]);
        }
    }
    </script>
    </head>
    <body>
    <p>Hello</p>
    </body>
    </html>

Chapter 13

  1. See Example 13-2 in Chapter 13 for an example of this exercise.

  2. Within the slideshow example, there is a function called nextimage(). That's where the changes should be made for this exercise. The changes are shown in bold here.

    function nextimage() {
        var img = document.getElementById("slideimage");
        var imgname = img.name.split("_");
        var index = imgname[1];
        if (index == images.length - 1) {
            var startover = confirm(
                "You've reached the last image. Start over from the beginning?");
            if (startover) {
                index = 0;
            } else {
                return;
            }
        } else {
            index++;
        }
        img.src = images[index];
        img.name = "image_" + index;
    }
  3. See Example 13-2 in this chapter for an example of preloading images. That same code logic would be applied to the image map that you make for this exercise.

Chapter 14

  1. Here's the code:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>Onclick</title>
    <script type="text/javascript">
    function handleclick() {
        alert("You Clicked Here");
        return false;
    }
    
    </script>
    </head>
    <body>
    <p><a href="#" onclick="return handleclick();">Click Here</a></p>
    </body>
    </html>
  2. Here's the code:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    
    <title>Onclick</title>
    <script type="text/javascript">
    function handleclick() {
        alert("You Clicked Here");
        return false;
    }
    
    </script>
    </head>
    <body>
    <p><a id="link1" href="#">Click Here</a></p>
    <script type = "text/javascript" >
    var link1 = document.getElementById("link1");
    if (typeof window.addEventListener != "undefined") {
        link1.addEventListener("click",handleclick,false);
    } else {
        link1.attachEvent("onclick",handleclick);
    }
    </script>
    
    </body>
    </html>
  3. No JavaScript is necessary for this. The code looks as follows:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>New Tab</title>
    </head>
    <body>
    <p><a target="Microsoft" href="http://www.microsoft.com" id="mslink-id001">Go To Microsoft
    </a></p>
    </body>
    </html>
  4. Here's the code:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>window open</title>
    <script type="text/javascript">
    function openwin(event) {
        if (typeof window.open != "undefined") {
            var opened =window.open(
                "http://www.braingia.org","",
    "height=300,width=250,menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=
    yes");
            event.preventDefault();
            return false;
        } else {
            return true;
        }
    }
    </script>
    </head>
    <body>
    <p><a target="Microsoft" href="http://www.microsoft.com" id="mslink-id002">Go To Microsoft
    </a></p>
    <p id="braingia"><a href="DYNAMIC URL GOES HERE" id="braingialink-id002">
    Go To Steve Suehring's Page</a></p>
    <script type = "text/javascript">
    var braingialink = document.getElementById("braingialink");
    if (window.addEventListener) {
        braingialink.addEventListener("click",openwin,false);
    } else {
        braingialink.attachEvent("onclick",openwin);
    }
    </script>
    </body>
    </html>

Chapter 15

  1. Here's an example page:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>CSS</title>
    </head>
    <body>
    <h1 id="h1element">The Title</h1>
    <p id="firstelement">The first element.</p>
    <p id="secondelement">The second element.</p>
    </body>
    </html>
  2. This code will change the element named firstelement so that its font color is blue:

    <script type = "text/javascript" >
    var element1 = document.getElementById("firstelement");
    element1.style.color = "#0000FF";
    </script>
  3. This code hides all the <p> elements using the Cascading Style Sheets (CSS) visibility property:

    <script type = "text/javascript" >
    var pelements = document.getElementsByTagName("p");
    for (var i = 0; i < pelements.length; i++) {
        pelements[i].style.visibility = "hidden";
    }
    </script>
  4. This code shows the visibility setting both before and after it has been set within the script. When you run the code, notice that the alert is empty prior to the property being set.

    <script type = "text/javascript" >
    var pelements = document.getElementsByTagName("p");
    for (var i = 0; i < pelements.length; i++) {
        alert(pelements[i].style.visibility);
        pelements[i].style.visibility = "hidden";
        alert(pelements[i].style.visibility);
    }
    </script>
  5. This solution uses the form.htm file found in Chapter 15:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>Form Validation</title>
    <script type="text/javascript" src="form.js"></script>
    </head>
    <body>
    <form name="formexample" id="formexample-id001" action="#">
    <div id="citydiv-id003">City: <input id="city-id002" name="city"></div>
    <div><input id="submit-id003" type="submit"></div>
    </form>
    <script type="text/javascript">
        function init() {
            document.forms[0].onsubmit = function() { return checkValid() };
        }
        window.onload = init;
    </script>
    </body>
    </html>

    The form.js file is where the new element with the error text is created and appended. Here it is, with the additional lines shown in bold type:

    function checkValid() {
        var cityField = document.forms[0]["city"];
        if (cityField.value != "Stevens Point") {
            cityField.style.background = "#FF0000";
            var citydiv = document.getElementById("citydiv");
            var feedbackdiv = document.createElement("div");
            feedbackdiv.setAttribute("id","feedback");
            citydiv.appendChild(feedbackdiv);
            feedbackdiv.appendChild(document.createTextNode("Incorrect City."));
            return false;
        } else {
            return true;
        }
    }

Chapter 16

  1. Example 16-1 in Chapter 16 provides a solution for this exercise.

  2. An alert provides visual feedback, so that works as a solution to this problem. Better visual feedback can be found in the solution to Exercise 5 in Chapter 15, shown previously, where a new element was used. Here's the basic solution to this problem:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>Try/Catch</title>
    <script type="text/javascript">
    </script>
    </head>
    <body>
    <form name="formexample" id="formexample-id003" action="#">
    <div id="citydiv-id004">Enter a City: <input id="city-id003" name="city"></div>
    <div><input id="submit-id004" type="submit"></div>
    </form>
    <script type="text/javascript">
    function checkValid() {
        try {
            var cityField = document.forms[0]["city"];
            if (cityField.value != "Stockholm") {
                throw "It's not Stockholm";
            }
        }
        catch(errorObject) {
            alert(errorObject);
        }
    }
    function init() {
        document.forms[0].onsubmit = function() { return checkValid() };
    }
    window.onload = init;
    </script>
    </body>
    </html>
  3. Here's the code:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>Try/Catch</title>
    <script type="text/javascript">
    </script>
    </head>
    <body>
    <form name="formexample" id="formexample-id004" action="#">
    <div id="citydiv-id005">Enter a Number Between 1 and 100: <input id="num-id001" name="num"></div>
    <div><input id="submit-id005" type="submit"></div>
    </form>
    <script type="text/javascript">
    function checkValid() {
        try {
            var numField = document.forms[0]["num"];
            if (isNaN(numField.value)) {
                throw "it's not a number";
            }
            if ((numField.value > 100) || (numField.value < 1)) {
                numField.style.background = "#FF0000";
                return false;
            }
            else {
                numField.style.background = "#FFFFFF";
                return true;
            }
        }
        catch(errorObject) {
            alert(errorObject);
        }
        finally {
            alert("Thank you for playing.");
        }
    }
    function init() {
        document.forms[0].onsubmit = function() { return checkValid() };
    }
    window.onload = init;
    </script>
    </body>
    </html>

Chapter 17

  1. This solution requires the books.htm and books.xml files that are used within Chapter 17. Only books.htm is changed for the solution. The few changes to this file are highlighted in bold.

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>Books</title>
    </head>
    <body>
    <div id="xmldata-id003"></div>
    <p><a href="#" id="displaytable">Display Table</a></p>
    <script type="text/javascript">
    var tablelink = document.getElementById("displaytable");
    if (typeof window.addEventListener != "undefined") {
        tablelink.addEventListener("click",getXML,false);
    } else {
        tablelink.attachEvent("onclick",getXML);
    }
    
    
    function displayData() {
        var xmlEl = docObj.getElementsByTagName("book");
        var table = document.createElement("table");
        table.border = "1";
        var tbody = document.createElement("tbody");
    
        // Append the body to the table
        table.appendChild(tbody);
        var row = document.createElement("tr");
    
        for (colHead = 0; colHead < xmlEl[0].childNodes.length; colHead++) {
            if (xmlEl[0].childNodes[colHead].nodeType != 1) {
                continue;
            }
            var tableHead = document.createElement("th");
            var colName = document.createTextNode(xmlEl[0].childNodes[colHead].nodeName);
            tableHead.appendChild(colName);
            row.appendChild(tableHead);
        }
        tbody.appendChild(row);
    
    
        // Create table row
        for (i = 0; i < xmlEl.length; i++) {
            var row = document.createElement("tr");
            // Create the row/td elements
            for (j = 0; j < xmlEl[i].childNodes.length; j++) {
                // Skip it if the type is not 1
                if (xmlEl[i].childNodes[j].nodeType != 1) {
                    continue;
                }
    
                // Insert the actual text/data from the XML document.
                var td = document.createElement("td");
                var xmlData = document.createTextNode(xmlEl[i].childNodes[j].firstChild.
    nodeValue);
                td.appendChild(xmlData);
                row.appendChild(td);
            }
            tbody.appendChild(row);
        }
        document.getElementById("xmldata").appendChild(table);
    }
    
    function getXML()
    {
        tablelink.style.visibility = "hidden";
        if (typeof document.implementation.createDocument != "undefined")
        {
            docObj = document.implementation.createDocument("", "", null);
            docObj.onload = displayData;
        }
        else if (window.ActiveXObject)
        {
            docObj = new ActiveXObject("Microsoft.XMLDOM");
            docObj.onreadystatechange = function () {
                if (docObj.readyState == 4) displayData()
            };
        }
        docObj.load("books.xml");
    }
    
    </script>
    </body>
    </html>

    Bonus: The following code adds a "Display Table" link, and then, when the table is displayed, it adds a "Hide Table" link. This wasn't part of the exercise.

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>Books</title>
    </head>
    <body>
    <div id="xmldata-id004"></div>
    <p><a href="#" id="displaytable-id001">Display Table</a></p>
    <script type="text/javascript">
    
    var tablelink = document.getElementById("displaytable");
    if (typeof window.addEventListener != "undefined") {
        tablelink.addEventListener("click",getXML,false);
    } else {
        tablelink.attachEvent("onclick",getXML);
    }
    
    
    function displayData() {
        var xmlEl = docObj.getElementsByTagName("book");
        var table = document.createElement("table");
        table.setAttribute("id","bookstable");
        table.border = "1";
        var tbody = document.createElement("tbody");
    
        // Append the body to the table
        table.appendChild(tbody);
        var row = document.createElement("tr");
    
        for (colHead = 0; colHead < xmlEl[0].childNodes.length; colHead++) {
            if (xmlEl[0].childNodes[colHead].nodeType != 1) {
                continue;
            }
            var tableHead = document.createElement("th");
            var colName = document.createTextNode(xmlEl[0].childNodes[colHead].nodeName);
            tableHead.appendChild(colName);
            row.appendChild(tableHead);
        }
        tbody.appendChild(row);
    
    
        // Create table row
        for (i = 0; i < xmlEl.length; i++) {
            var row = document.createElement("tr");
            // Create the row/td elements
            for (j = 0; j < xmlEl[i].childNodes.length; j++) {
                // Skip it if the type is not 1
                if (xmlEl[i].childNodes[j].nodeType != 1) {
                    continue;
                }
    
                // Insert the actual text/data from the XML document.
                var td = document.createElement("td");
                var xmlData = document.createTextNode(xmlEl[i].childNodes[j].firstChild.
    nodeValue);
                td.appendChild(xmlData);
                row.appendChild(td);
            }
            tbody.appendChild(row);
        }
        var tableanchor = document.createElement("a");
        var tableanchortext = document.createTextNode("Hide Table");
        tableanchor.setAttribute("id","hidetable");
        tableanchor.setAttribute("href","#");
        tableanchor.appendChild(tableanchortext);
        if (typeof window.addEventListener != "undefined") {
            tableanchor.addEventListener("click",hideTable,false);
        } else {
            tableanchor.attachEvent("onclick",hideTable);
        }
        document.getElementById("xmldata").appendChild(tableanchor);
        document.getElementById("xmldata").appendChild(table);
    }
    
    function hideTable() {
        var bookstable = document.getElementById("bookstable");
        bookstable.style.display = "none";
        tablelink.style.display = "";
        var tableanchor = document.getElementById("hidetable");
        tableanchor.style.display = "none";
    }
    
    function getXML()
    {
        tablelink.style.display = "none";
        if (typeof document.implementation.createDocument != "undefined")
        {
            docObj = document.implementation.createDocument("", "", null);
            docObj.onload = displayData;
        }
        else if (window.ActiveXObject)
        {
            docObj = new ActiveXObject("Microsoft.XMLDOM");
            docObj.onreadystatechange = function () {
                if (docObj.readyState == 4) displayData()
            };
        }
        docObj.load("books.xml");
    }
    
    </script>
    </body>
    </html>
  2. This solution requires the books.xml file as well. Most of the code is the same as the final books.htm code in Chapter 17, with the differences shown in bold:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>Books</title>
    </head>
    <body>
    <div id="xmldata-id001"></div>
    <script type="text/javascript">
    
    window.onload = getXML;
    
    function displayData() {
        var xmlEl = docObj.getElementsByTagName("book");
        var table = document.createElement("table");
        table.border = "1";
        var tbody = document.createElement("tbody");
    
        // Append the body to the table
        table.appendChild(tbody);
        var row = document.createElement("tr");
    
        for (colHead = 0; colHead < xmlEl[0].childNodes.length; colHead++) {
            if (xmlEl[0].childNodes[colHead].nodeType != 1) {
                continue;
            }
            var tableHead = document.createElement("th");
            var colName = document.createTextNode(xmlEl[0].childNodes[colHead].nodeName);
            tableHead.appendChild(colName);
            row.appendChild(tableHead);
        }
        tbody.appendChild(row);
    
    
        // Create table row
        for (i = 0; i < xmlEl.length; i++) {
            var row = document.createElement("tr");
            // Create the row/td elements
            for (j = 0; j < xmlEl[i].childNodes.length; j++) {
                // Skip it if the type is not 1
                if (xmlEl[i].childNodes[j].nodeType != 1) {
                    continue;
                }
    
                // Insert the actual text/data from the XML document.
                var td = document.createElement("td");
                if (i % 2) {
                    td.style.background = "#aaabba";
                }
                var xmlData = document.createTextNode(xmlEl[i].childNodes[j].firstChild.
    nodeValue);
                td.appendChild(xmlData);
                row.appendChild(td);
            }
            tbody.appendChild(row);
        }
        document.getElementById("xmldata").appendChild(table);
    }
    
    function getXML()
    {
        if (typeof document.implementation.createDocument != "undefined")
        {
            docObj = document.implementation.createDocument("", "", null);
            docObj.onload = displayData;
        }
        else if (window.ActiveXObject)
        {
            docObj = new ActiveXObject("Microsoft.XMLDOM");
            docObj.onreadystatechange = function () {
                if (docObj.readyState == 4) displayData()
            };
        }
        docObj.load("books.xml");
    }
    
    </script>
    </body>
    </html>
  3. False. Browsers that are compliant with the World Wide Web Consortium (W3C) requirements use different methods than Microsoft Windows Internet Explorer does.

  4. False. Before you can work with XML data, you must wait for readyState to be equal to 4.

Chapter 18

  1. None of the Hypertext Transfer Protocol (HTTP) methods discussed in the chapter offer more security than any of the others. Only the addition of Secure Sockets Layer (SSL) adds a layer of security on top of the HTTP methods. It should be noted that using the POST method does not hide the input data, and only the POST method should be used with SSL because the GET method would place the parameters right on the URL where they could be seen regardless of SSL.

  2. Responses using standard HTML are retrieved with the responseText method and can contain just about anything that could be obtained through HTTP. Extensible Markup Language (XML) responses must be obtained with the responseXML method and must be served as an XML content type by the server. JavaScript Object Notation (JSON) responses are JavaScript responses; therefore, they offer some performance advantages over the other methods.

  3. This solution was discussed in the chapter itself, but here is the asynchronous call (replace YOUR SERVER appropriately for your environment):

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>Async</title>
    </head>
    <body>
    <div id="xmldata-id005"></div>
    <script type="text/javascript">
    function readyAJAX() {
    try {
        return new XMLHttpRequest();
    } catch(e) {
        try {
            return new ActiveXObject('Msxml2.XMLHTTP'),
        } catch(e) {
            try {
                return new ActiveXObject('Microsoft.XMLHTTP'),
            } catch(e) {
                return "A newer browser is needed.";
            }
        }
    }
    }
    var requestObj = readyAJAX();
    var url ="http://YOUR SERVER/sum.php?num1=2&num2=2";
    requestObj.open("GET",url,true);
    requestObj.send();
    requestObj.onreadystatechange = function() {
        if (requestObj.readyState == 4) {
            if (requestObj.status == 200) {
                alert(requestObj.responseText);
            } else {
                alert(requestObj.statusText);
            }
        }
    }
    </script>
    </body>
    </html>

    The file sum.php is a woefully small and inadequately secured server-side program in PHP that looks like this:

    <?php
    print $_GET['num1'] + $_GET['num2'];
    ?>

Chapter 19

  1. This solution uses Example 19-1 and requires the addition of a submit button to the form. The form now looks like this:

    <form name="nameform" id="nameform-id003" action="" method="GET">
    Enter State: <input id="textname-id003" type="text" name="textname">
    <input type="submit" name="submit" id="statesubmit">
    </form>

    An event handler and new function are all that's required for this solution. These are added within the existing JavaScript.

    var submitbtn = document.getElementById("nameform");
    if (window.addEventListener) {
        submitbtn.addEventListener("submit",showstate,false);
    } else {
        submitbtn.attachEvent("onsubmit",showstate);
    }
    
    function showstate() {
        alert(document.forms[0].textname.value);
    }
  2. This solution is a variation of the previous solution and others shown in Chapter 19. The server-side program will need to return the comma-delimited list of people for the company directory, much as the state example returned a list of U.S. states.

  3. Congratulations!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.190.159.10