SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Aug 2006
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    HTML Radio group and the javascript switch statement

    How would I perform a switch operation on a radio group?

    Ie I have a group of radio group inputs as such

    <input type="radio" name="myRadioGroup" value="1">
    <input type="radio" name="myRadioGroup" value="2">
    <input type="radio" name="myRadioGroup" value="3">

    How would I do a switch against the radiogroup and it's values, ie(psuedo-code below)

    switch(myRadioGroup.value) {
    case "1": dostuff(); break
    case "2": dostuff(); break
    case "3": dostuff(); break
    }

    Most people would say just use an if statement, well yes I can do that, and I tried that, but I"m trying to shorten and optimize my code by using switch statements where applicable.

    The problem I"m running into is that the MyRadioGroup is a javascript Object.

    Is there a way to do what I"m trying to do in javascript without resorting to staying with if statements?

  2. #2
    SitePoint Member therealfiredog69's Avatar
    Join Date
    Aug 2006
    Posts
    13
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    First you need to add an onClick() to your <input> tags that call a function sending the value.

    Your function will accept the value. Then using your switch(), you can do what you want...

    HTML Code:
    <html>
    <head>
         <title></title>
         <script language="javascript" type="text/javascript">
         <!-- Hide from Non-Javascript browsers
         function doIt(the_value)
         {
               switch(the_value)
               {
                   case "1":
                        document.getElementById('myDIV').innerHTML="One";
                        break;
    
                   case "2":
                        document.getElementById('myDIV').innerHTML="Two";
                        break;
    
                   case "3":
                        document.getElementById('myDIV').innerHTML="Three";
                        break;
                   
                   default:
                        document.getElementById('myDIV').innerHTML="Default";
               }
         }
    
         // Stop Hiding -->
         </script>
    </head>
    
    <body>
    <form name="myform">
         <input type="radio" name="myRadioGroup" value="1" onClick="doIt(this.value);" />
         <input type="radio" name="myRadioGroup" value="2" onClick="doIt(this.value);" />
         <input type="radio" name="myRadioGroup" value="3" onClick="doIt(this.value);" />
    </form>
    
    <br /><br />
    
    <div id="myDIV">
         &nbsp;
    </div>
    
    </body>
    </html>


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •