using a switch case and buttons, but onclick doesnt seem to work

Discussion in 'JavaScript' started by Fred3, Nov 29, 2006.

  1. #1
    I am trying to create a script based on the example of multi level conditionals found here:

    http://www.samspublishing.com/articles/article.asp?p=676586&seqNum=9&rl=1

    however when I remove the "initAll" function, and replace it with simple onclick="saySomething(this)" in the buttons, it stops working. I am correct in thinking the initAll simply gives buttons the property onclick, right?

    If anyone can offer any solutions or ideas as to getting it working I would appreciate it infinitely.

    Heres the HTML
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
         <title>Switch/Case handling</title>
         <script language="Javascript" type="text/javascript" src="script09.js">
         </script>
    </head>
    <body bgcolor="#FFFFFF">
    <h2>Famous Presidential Quotes</h2>
    <form action="#">
         <input type="button" value="Lincoln" />
         <input type="button" value="Kennedy" />
         <input type="button" value="Nixon" />
    </form>
    </body>
    </html>
    
    Code (markup):
    and heres the JS
    
    window.onload = initAll;
    function initAll() {
         for (var i=0; i< document.forms[0]. elements.length; i++) {
            var thisElement = document.forms[0]. elements[i];
    
            if (thisElement.type == "button") {
               thisElement.onclick = saySomething;
            }
         }
    }
    
    function saySomething() {
         switch(this.value) {
            case "Lincoln":
               alert("Four score and seven years ago...");
               break;
            case "Kennedy":
               alert("Ask not what your country can do for you...");
               break;
            case "Nixon":
               alert("I am not a crook!");
               break;
            default:
         }
    }
    
    Code (markup):

     
    Fred3, Nov 29, 2006 IP