Page 1 of 1

Switch statement doesn't work

Posted: Fri Dec 11, 2009 7:22 am
by finchamgroves
Hi
The following code worked fine in FF and IE but always produces the first option in Safari.
(The CDATA statment doesn't make any difference to the outcome.)
Any advice very, very welcome!

Code: Select all

 
<html>
<head>
<script type="text/javascript">
/* <![CDATA[ */
var my_text;
var talk_01 = 'text stuff 1';
var talk_02 = 'text stuff 2';
var talk_03 = 'text stuff 3';
function speaker(talk)
    {
    switch(talk)
        {
        case(talk=1):
        my_text = talk_01;
        break;
        case(talk=2):
        my_text = talk_02;
        break;
        case(talk=3):
        my_text = talk_03;
        break;
        }
    document.getElementById('infobox').innerHTML = my_text;
    }
/*]]>*/
</script>
</head>
<body>
    <table width="85%" align="center" class="myTable1" summary="speaker table">
              <tr>
                <th><div align="left">Date</div></th>
                <th><div align="left">Speaker</div></th>
                <th><div align="left">Topic</div></th>
                <th>&nbsp;</th>
              </tr>
              <tr class='hilite'>
                <td>January 28th</td>
                <td>Aristotle</td>
                <td>Aardvarks</td>
                <td  onclick="speaker(1)">more ... </td>
              </tr>
              <tr class='hilite'>
                <td>February 25th</td>
                <td>Benjamin</td>
                <td>Butterflies</td>
                <td onclick="speaker(2)">more ... </td>
              </tr>
              <tr class='hilite'>
                <td>March 25th</td>
                <td>Canute</td>
                <td>Canoes</td>
                <td  onclick="speaker(3)">more ... </td>
              </tr>
      </table>
      <div id ="infobox"> 
        <p>
            Click <strong><em>more</em></strong>... in the above Table for more info about the talks. </p>
        <p>(If you use Internet Explorer you may need to click on a script warning at the top of your screen) </p>
      </div>
</body>
</html>
 

Re: Switch statement doesn't work

Posted: Fri Dec 11, 2009 9:25 am
by papa
Shouldn't it be case(talk==1): ?

Re: Switch statement doesn't work

Posted: Fri Dec 11, 2009 9:31 am
by VladSun
Why one should even compare values in a case statement ???

http://www.w3schools.com/js/js_switch.asp

http://php.net/manual/en/control-structures.switch.php
Example 1!

Re: Switch statement doesn't work

Posted: Fri Dec 11, 2009 9:35 am
by papa
True :)

Re: Switch statement doesn't work

Posted: Fri Dec 11, 2009 9:43 am
by finchamgroves
No it isn't ==
But thanks because you focussed me in the correct place.
It's

Code: Select all

 
        case 1:
        my_text = talk_01;
        break;
        case 2:
etc
 
And this has got it working in all browsers.
Cheers! :D :D :D