case statements in Javascript

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Navodit

    case statements in Javascript

    So I have some code like:

    if (document.Insur ance.State.sele ctedIndex == 1)
    {
    ifIll();
    }
    else if (document.Insur ance.State.sele ctedIndex == 2)
    {
    elseKan();
    }
    else if (document.Insur ance.State.sele ctedIndex == 3)
    {
    elseInd();
    }

    I am trying to replace the if-else statements with case statement as
    follows:

    var index = document.Insura nce.State.selec tedIndex;

    switch (index)
    {
    case 1:
    ifIll()
    break
    case 2:
    elseKan()
    break
    case 3: elseInd()
    break
    }

    This code doesn't work ! Am I missing something here? Thanks


  • Daz

    #2
    Re: case statements in Javascript

    On Apr 16, 4:41 pm, "Navodit" <kaush...@uiuc. eduwrote:
    So I have some code like:
    >
    if (document.Insur ance.State.sele ctedIndex == 1)
    {
    ifIll();}
    >
    else if (document.Insur ance.State.sele ctedIndex == 2)
    {
    elseKan();}
    >
    else if (document.Insur ance.State.sele ctedIndex == 3)
    {
    elseInd();
    >
    }
    >
    I am trying to replace the if-else statements with case statement as
    follows:
    >
    var index = document.Insura nce.State.selec tedIndex;
    >
    switch (index)
    {
    case 1:
    ifIll()
    break
    case 2:
    elseKan()
    break
    case 3: elseInd()
    break
    >
    }
    >
    This code doesn't work ! Am I missing something here? Thanks
    I can't see the problem myself. I would recommend you either get a
    good debugger (Firebug for Firefox is awesome), or that you add a
    default: case to catch anything that falls off the end of the case,
    which can alert as to what value was passed to the switch case, if
    any. Also, it might be useful to use some try/catch clauses in there
    somewhere, that way you will be notified of any errors.

    All the best.

    Daz.

    Comment

    • Daz

      #3
      Re: case statements in Javascript

      On Apr 16, 4:41 pm, "Navodit" <kaush...@uiuc. eduwrote:
      So I have some code like:
      >
      if (document.Insur ance.State.sele ctedIndex == 1)
      {
      ifIll();}
      >
      else if (document.Insur ance.State.sele ctedIndex == 2)
      {
      elseKan();}
      >
      else if (document.Insur ance.State.sele ctedIndex == 3)
      {
      elseInd();
      >
      }
      >
      I am trying to replace the if-else statements with case statement as
      follows:
      >
      var index = document.Insura nce.State.selec tedIndex;
      >
      switch (index)
      {
      case 1:
      ifIll()
      break
      case 2:
      elseKan()
      break
      case 3: elseInd()
      break
      >
      }
      >
      This code doesn't work ! Am I missing something here? Thanks
      Oh, and another thing you should be aware of, is the type of the
      argument you are passing to the switch case. You could be passing a
      string instead of an integer, in which case you switch case should
      look like this:

      switch (index) {

      case "1":
      ifIll();
      break;

      case "2":
      elseKan();
      break;

      case "3":
      elseInd();
      break;
      }

      NOT this:

      switch (index) {

      case 1:
      ifIll();
      break;

      case 2:
      elseKan();
      break;

      case 3:
      elseInd();
      break;
      }

      In either case (no pun intended), you should use a default case to
      catch anything that drops through the case, unless you specifically
      want them to be ignored.

      Comment

      • Evertjan.

        #4
        Re: case statements in Javascript

        Navodit wrote on 16 apr 2007 in comp.lang.javas cript:
        So I have some code like:
        >
        if (document.Insur ance.State.sele ctedIndex == 1)
        {
        ifIll();
        >}
        else if (document.Insur ance.State.sele ctedIndex == 2)
        {
        elseKan();
        >}
        else if (document.Insur ance.State.sele ctedIndex == 3)
        {
        elseInd();
        >}
        >
        I am trying to replace the if-else statements with case statement as
        follows:
        >
        var index = document.Insura nce.State.selec tedIndex;
        >
        switch (index)
        {
        case 1:
        ifIll()
        break
        case 2:
        elseKan()
        break
        case 3: elseInd()
        break
        >}
        >
        This code doesn't work ! Am I missing something here? Thanks
        Probably you did, as this works fine:

        =============== =============== ==========
        <script type='text/javascript'>
        function ch(x){
        switch (x.selectedInde x) {
        case 1:
        alert('one');
        break;
        case 2:
        alert('two');
        break;
        case 3:
        alert('three');
        break;
        };
        };
        </script>

        <select onchange='ch(th is)'>
        <option--
        <option1
        <option2
        <option3
        </select>
        =============== =============== ==========




        --
        Evertjan.
        The Netherlands.
        (Please change the x'es to dots in my emailaddress)

        Comment

        • Lee

          #5
          Re: case statements in Javascript

          Navodit said:
          >I am trying to replace the if-else statements with case statement as
          >follows:
          >
          >var index = document.Insura nce.State.selec tedIndex;
          >
          >switch (index)
          >{
          case 1:
          ifIll()
          break
          case 2:
          elseKan()
          break
          case 3: elseInd()
          break
          >}
          >
          >This code doesn't work ! Am I missing something here? Thanks
          What does "doesn't work" mean? Are you seeing error messages?
          Is something unexpected happening?
          Those are really lousy choices for function names, by the way,
          and are you sure you really need a separate function for each
          state?


          --

          Comment

          • Daz

            #6
            Re: case statements in Javascript

            On Apr 16, 5:21 pm, Lee <REM0VElbspamt. ..@cox.netwrote :
            Navodit said:
            >
            >
            >
            I am trying to replace the if-else statements with case statement as
            follows:
            >
            var index = document.Insura nce.State.selec tedIndex;
            >
            switch (index)
            {
            case 1:
            ifIll()
            break
            case 2:
            elseKan()
            break
            case 3: elseInd()
            break
            }
            >
            This code doesn't work ! Am I missing something here? Thanks
            >
            What does "doesn't work" mean? Are you seeing error messages?
            Is something unexpected happening?
            Those are really lousy choices for function names, by the way,
            and are you sure you really need a separate function for each
            state?
            >
            --
            In the OP's defense, I believe he's just trying to reverse engineer
            the "if" statements, and he's testing it at each phase. To me, that's
            a sensible approach, and I am sure that once the switch case does what
            he's expecting it to do, he will no doubt change the function names.
            Also, depending on the size of the functions needed to process the
            data, I usually prefer keeping functions separate, as I find it's a
            lot easier to organise code. I guess preferences differ...

            Comment

            • Navodit

              #7
              Re: case statements in Javascript


              "Daz" <cutenfuzzy@gma il.comwrote in message
              news:1176740779 .744669.248400@ b75g2000hsg.goo glegroups.com.. .
              On Apr 16, 5:21 pm, Lee <REM0VElbspamt. ..@cox.netwrote :
              >Navodit said:
              >>
              >>
              >>
              >I am trying to replace the if-else statements with case statement as
              >follows:
              >>
              >var index = document.Insura nce.State.selec tedIndex;
              >>
              >switch (index)
              >{
              case 1:
              ifIll()
              break
              case 2:
              elseKan()
              break
              case 3: elseInd()
              break
              >}
              >>
              >This code doesn't work ! Am I missing something here? Thanks
              >>
              >What does "doesn't work" mean? Are you seeing error messages?
              >Is something unexpected happening?
              >Those are really lousy choices for function names, by the way,
              >and are you sure you really need a separate function for each
              >state?
              >>
              >--
              >
              In the OP's defense, I believe he's just trying to reverse engineer
              the "if" statements, and he's testing it at each phase. To me, that's
              a sensible approach, and I am sure that once the switch case does what
              he's expecting it to do, he will no doubt change the function names.
              Also, depending on the size of the functions needed to process the
              data, I usually prefer keeping functions separate, as I find it's a
              lot easier to organise code. I guess preferences differ...
              >
              Thanks for all the feedback and comments. First of all I have not written
              those function names, my job is first to clean up the code as much as
              possible and then think about renaming. Each of those functions corresponds
              to around 50-100 lines of code so it is indeed useful to have them as
              separate functions. Each of those functions populates dropdown with counties
              for that particular state so when i say it doesnt work that implies the
              dropdown doesn't get populated when I use the case statement while it does
              get populated if the if statements are used.

              So essentially this works:

              if (document.Insur ance.State.sele ctedIndex == 1)
              {
              ifIll();
              }
              else if (document.Insur ance.State.sele ctedIndex == 2)
              {
              elseKan();
              }
              else if (document.Insur ance.State.sele ctedIndex == 3)
              {
              elseInd();
              }
              else if (document.Insur ance.State.sele ctedIndex == 4)
              {
              elseIw();
              }
              else if (document.Insur ance.State.sele ctedIndex == 6)
              {
              elseMich();
              }
              else if (document.Insur ance.State.sele ctedIndex == 7)
              {
              elseMin();
              }
              else if (document.Insur ance.State.sele ctedIndex == 8)
              {
              elseMis();
              }
              else if (document.Insur ance.State.sele ctedIndex == 9)
              {
              elseNeb();
              }
              else if (document.Insur ance.State.sele ctedIndex == 10)
              {
              elseND();
              }
              else if (document.Insur ance.State.sele ctedIndex == 11)
              {
              elseOh();
              }
              else if (document.Insur ance.State.sele ctedIndex == 12)
              {
              elseSD();
              }
              else if (document.Insur ance.State.sele ctedIndex == 13)
              {
              elseWI();
              }
              else if (document.Insur ance.State.sele ctedIndex == 5)
              {
              elseMar();
              }

              and this doesn't:

              switch (document.Insur ance.State.sele ctedIndex)
              {
              case 1:
              ifIll();
              break;
              case 2:
              elseKan();
              break;
              case 3:
              elseInd();
              break;
              case 4:
              elseIw();
              break;
              case 5:
              elseMar();
              break;
              casce 6:
              elseMich();
              break;
              case 7:
              elseMin();
              break;
              case 8:
              elseMis();
              break;
              case 9:
              elseNeb();
              break;
              case 10:
              elseND();
              break;
              case 11:
              elseOh();
              break;
              case 12:
              elseSD();
              break;
              case 13:
              elseWI();
              break;
              default:
              break;
              }

              I also tried : case "1" etc and case '1' but that too doesnt work. Any
              further ideas? Thanks


              Comment

              • Daz

                #8
                Re: case statements in Javascript

                On Apr 16, 5:39 pm, "Navodit" <kaush...@uiuc. eduwrote:
                "Daz" <cutenfu...@gma il.comwrote in message
                >
                news:1176740779 .744669.248400@ b75g2000hsg.goo glegroups.com.. .
                >
                >
                >
                On Apr 16, 5:21 pm, Lee <REM0VElbspamt. ..@cox.netwrote :
                Navodit said:
                >
                I am trying to replace the if-else statements with case statement as
                follows:
                >
                var index = document.Insura nce.State.selec tedIndex;
                >
                switch (index)
                {
                case 1:
                ifIll()
                break
                case 2:
                elseKan()
                break
                case 3: elseInd()
                break
                }
                >
                This code doesn't work ! Am I missing something here? Thanks
                >
                What does "doesn't work" mean? Are you seeing error messages?
                Is something unexpected happening?
                Those are really lousy choices for function names, by the way,
                and are you sure you really need a separate function for each
                state?
                >
                --
                >
                In the OP's defense, I believe he's just trying to reverse engineer
                the "if" statements, and he's testing it at each phase. To me, that's
                a sensible approach, and I am sure that once the switch case does what
                he's expecting it to do, he will no doubt change the function names.
                Also, depending on the size of the functions needed to process the
                data, I usually prefer keeping functions separate, as I find it's a
                lot easier to organise code. I guess preferences differ...
                >
                Thanks for all the feedback and comments. First of all I have not written
                those function names, my job is first to clean up the code as much as
                possible and then think about renaming. Each of those functions corresponds
                to around 50-100 lines of code so it is indeed useful to have them as
                separate functions. Each of those functions populates dropdown with counties
                for that particular state so when i say it doesnt work that implies the
                dropdown doesn't get populated when I use the case statement while it does
                get populated if the if statements are used.
                >
                So essentially this works:
                >
                if (document.Insur ance.State.sele ctedIndex == 1)
                {
                ifIll();}
                >
                else if (document.Insur ance.State.sele ctedIndex == 2)
                {
                elseKan();}
                >
                else if (document.Insur ance.State.sele ctedIndex == 3)
                {
                elseInd();}
                >
                else if (document.Insur ance.State.sele ctedIndex == 4)
                {
                elseIw();}
                >
                else if (document.Insur ance.State.sele ctedIndex == 6)
                {
                elseMich();}
                >
                else if (document.Insur ance.State.sele ctedIndex == 7)
                {
                elseMin();}
                >
                else if (document.Insur ance.State.sele ctedIndex == 8)
                {
                elseMis();}
                >
                else if (document.Insur ance.State.sele ctedIndex == 9)
                {
                elseNeb();}
                >
                else if (document.Insur ance.State.sele ctedIndex == 10)
                {
                elseND();}
                >
                else if (document.Insur ance.State.sele ctedIndex == 11)
                {
                elseOh();}
                >
                else if (document.Insur ance.State.sele ctedIndex == 12)
                {
                elseSD();}
                >
                else if (document.Insur ance.State.sele ctedIndex == 13)
                {
                elseWI();}
                >
                else if (document.Insur ance.State.sele ctedIndex == 5)
                {
                elseMar();
                >
                }
                >
                and this doesn't:
                >
                switch (document.Insur ance.State.sele ctedIndex)
                {
                case 1:
                ifIll();
                break;
                case 2:
                elseKan();
                break;
                case 3:
                elseInd();
                break;
                case 4:
                elseIw();
                break;
                case 5:
                elseMar();
                break;
                casce 6:
                elseMich();
                break;
                case 7:
                elseMin();
                break;
                case 8:
                elseMis();
                break;
                case 9:
                elseNeb();
                break;
                case 10:
                elseND();
                break;
                case 11:
                elseOh();
                break;
                case 12:
                elseSD();
                break;
                case 13:
                elseWI();
                break;
                default:
                break;
                >
                }
                >
                I also tried : case "1" etc and case '1' but that too doesnt work. Any
                further ideas? Thanks
                Try adding:

                alert(index); to your default case before the break. As I mentioned
                before, if none of the other cases fire, the default will. If it
                doesn't, then your problem is not with the contents of the switch
                case, but rather the fact that it's not being called at all. If this
                is the case, you should backtrack a little, and add alerts at in
                various places before the switch case, to make sure that the correct
                variable is being passed. My quess is that a null value is being
                passed to the switch case, in which case, the default case should pick
                it up, and the alert clause should tell you what's what.

                If you are still having problems, please Email me a copy of the code
                you wish to clean up, and I will be happy to help further.

                Comment

                • Lee

                  #9
                  Re: case statements in Javascript

                  Navodit said:
                  >Thanks for all the feedback and comments. First of all I have not written
                  >those function names, my job is first to clean up the code as much as
                  >possible and then think about renaming. Each of those functions corresponds
                  >to around 50-100 lines of code so it is indeed useful to have them as
                  >separate functions. Each of those functions populates dropdown with counties
                  >for that particular state so when i say it doesnt work that implies the
                  >dropdown doesn't get populated when I use the case statement while it does
                  >get populated if the if statements are used.
                  You haven't really made a case for separate functions.
                  If the functions differ only by what data they use, then
                  you should be using an array, rather than a switch.


                  --

                  Comment

                  • Lee

                    #10
                    Re: case statements in Javascript

                    Lee said:
                    >
                    >Navodit said:
                    >
                    >>Thanks for all the feedback and comments. First of all I have not written
                    >>those function names, my job is first to clean up the code as much as
                    >>possible and then think about renaming. Each of those functions corresponds
                    >>to around 50-100 lines of code so it is indeed useful to have them as
                    >>separate functions. Each of those functions populates dropdown with counties
                    >>for that particular state so when i say it doesnt work that implies the
                    >>dropdown doesn't get populated when I use the case statement while it does
                    >>get populated if the if statements are used.
                    >
                    >You haven't really made a case for separate functions.
                    >If the functions differ only by what data they use, then
                    >you should be using an array, rather than a switch.
                    Or, in this case, maybe a data structure built on Objects.
                    Here's a simplified example of what I mean:

                    <html>
                    <head>
                    <script type="text/javascript">
                    var stateData = {
                    IN: {
                    name: "Indiana",
                    capital: "Indianapol is",
                    counties: [ "Adams","Allen" ,"Bartholomew", "..." ]
                    },
                    IL: {
                    name: "Illinois",
                    capital: "Springfiel d",
                    counties: [ "Adams", "Alexander" , "Bond", "..." ]
                    },
                    KS: {
                    name: "Kansas",
                    capital: "Topeka",
                    counties: [ "Allen", "Anderson", "Atchison", "..." ]
                    }
                    }

                    function populateState(s el) {
                    if(sel.selected Index) {
                    var stateInfo=state Data[sel.options[sel.selectedInd ex].text];
                    msg="State: "+stateInfo.nam e+"\n"
                    +"Capital: "+stateInfo.cap ital+"\n"
                    +"Counties:\ n";
                    for(var i=0;i<stateInfo .counties.lengt h;i++) {
                    msg+=" "+stateInfo.cou nties[i]+"\n";
                    }
                    alert(msg);
                    }
                    }
                    </script>
                    </head>
                    <body>
                    <form>
                    <select onchange="popul ateState(this)" >
                    <option>Choos e a State</option>
                    <option>IL</option><option> KS</option><option> IN</option>
                    </select>
                    </form>
                    </body>
                    </html>


                    --

                    Comment

                    • Navodit

                      #11
                      Re: case statements in Javascript


                      "Lee" <REM0VElbspamtr ap@cox.netwrote in message
                      news:f00e9k02ao f@drn.newsguy.c om...
                      Lee said:
                      >>
                      >>Navodit said:
                      >>
                      >>>Thanks for all the feedback and comments. First of all I have not written
                      >>>those function names, my job is first to clean up the code as much as
                      >>>possible and then think about renaming. Each of those functions
                      >>>correspond s
                      >>>to around 50-100 lines of code so it is indeed useful to have them as
                      >>>separate functions. Each of those functions populates dropdown with
                      >>>counties
                      >>>for that particular state so when i say it doesnt work that implies the
                      >>>dropdown doesn't get populated when I use the case statement while it
                      >>>does
                      >>>get populated if the if statements are used.
                      >>
                      >>You haven't really made a case for separate functions.
                      >>If the functions differ only by what data they use, then
                      >>you should be using an array, rather than a switch.
                      >
                      Or, in this case, maybe a data structure built on Objects.
                      Here's a simplified example of what I mean:
                      >
                      <html>
                      <head>
                      <script type="text/javascript">
                      var stateData = {
                      IN: {
                      name: "Indiana",
                      capital: "Indianapol is",
                      counties: [ "Adams","Allen" ,"Bartholomew", "..." ]
                      },
                      IL: {
                      name: "Illinois",
                      capital: "Springfiel d",
                      counties: [ "Adams", "Alexander" , "Bond", "..." ]
                      },
                      KS: {
                      name: "Kansas",
                      capital: "Topeka",
                      counties: [ "Allen", "Anderson", "Atchison", "..." ]
                      }
                      }
                      >
                      function populateState(s el) {
                      if(sel.selected Index) {
                      var stateInfo=state Data[sel.options[sel.selectedInd ex].text];
                      msg="State: "+stateInfo.nam e+"\n"
                      +"Capital: "+stateInfo.cap ital+"\n"
                      +"Counties:\ n";
                      for(var i=0;i<stateInfo .counties.lengt h;i++) {
                      msg+=" "+stateInfo.cou nties[i]+"\n";
                      }
                      alert(msg);
                      }
                      }
                      </script>
                      </head>
                      <body>
                      <form>
                      <select onchange="popul ateState(this)" >
                      <option>Choos e a State</option>
                      <option>IL</option><option> KS</option><option> IN</option>
                      </select>
                      </form>
                      </body>
                      </html>
                      >
                      >
                      --
                      >
                      Thanks for the sample code. I think it does make more sense to use a data
                      structure instead of using functions. However I have a doubt:

                      In my case, I am not hardcoding ' counties' as shown in the example above
                      but I have stored it in an array 'county'. So when I am defining the data
                      structure what is the best way to set 'counties' for a state say 'IL' to be
                      equal to the array 'county'. Is it something like:

                      counties: county

                      or

                      counties = county

                      or something else?



                      Comment

                      • Daz

                        #12
                        Re: case statements in Javascript

                        On Apr 18, 5:26 pm, "Navodit" <kaush...@uiuc. eduwrote:
                        "Lee" <REM0VElbspamt. ..@cox.netwrote in message
                        >
                        news:f00e9k02ao f@drn.newsguy.c om...
                        >
                        >
                        >
                        Lee said:
                        >
                        >Navodit said:
                        >
                        >>Thanks for all the feedback and comments. First of all I have not written
                        >>those function names, my job is first to clean up the code as much as
                        >>possible and then think about renaming. Each of those functions
                        >>corresponds
                        >>to around 50-100 lines of code so it is indeed useful to have them as
                        >>separate functions. Each of those functions populates dropdown with
                        >>counties
                        >>for that particular state so when i say it doesnt work that implies the
                        >>dropdown doesn't get populated when I use the case statement while it
                        >>does
                        >>get populated if the if statements are used.
                        >
                        >You haven't really made a case for separate functions.
                        >If the functions differ only by what data they use, then
                        >you should be using an array, rather than a switch.
                        >
                        Or, in this case, maybe a data structure built on Objects.
                        Here's a simplified example of what I mean:
                        >
                        <html>
                        <head>
                        <script type="text/javascript">
                        var stateData = {
                        IN: {
                        name: "Indiana",
                        capital: "Indianapol is",
                        counties: [ "Adams","Allen" ,"Bartholomew", "..." ]
                        },
                        IL: {
                        name: "Illinois",
                        capital: "Springfiel d",
                        counties: [ "Adams", "Alexander" , "Bond", "..." ]
                        },
                        KS: {
                        name: "Kansas",
                        capital: "Topeka",
                        counties: [ "Allen", "Anderson", "Atchison", "..." ]
                        }
                        }
                        >
                        function populateState(s el) {
                        if(sel.selected Index) {
                        var stateInfo=state Data[sel.options[sel.selectedInd ex].text];
                        msg="State: "+stateInfo.nam e+"\n"
                        +"Capital: "+stateInfo.cap ital+"\n"
                        +"Counties:\ n";
                        for(var i=0;i<stateInfo .counties.lengt h;i++) {
                        msg+=" "+stateInfo.cou nties[i]+"\n";
                        }
                        alert(msg);
                        }
                        }
                        </script>
                        </head>
                        <body>
                        <form>
                        <select onchange="popul ateState(this)" >
                        <option>Choos e a State</option>
                        <option>IL</option><option> KS</option><option> IN</option>
                        </select>
                        </form>
                        </body>
                        </html>
                        >
                        --
                        >
                        Thanks for the sample code. I think it does make more sense to use a data
                        structure instead of using functions. However I have a doubt:
                        >
                        In my case, I am not hardcoding ' counties' as shown in the example above
                        but I have stored it in an array 'county'. So when I am defining the data
                        structure what is the best way to set 'counties' for a state say 'IL' to be
                        equal to the array 'county'. Is it something like:
                        >
                        counties: county
                        >
                        or
                        >
                        counties = county
                        >
                        or something else?
                        You can do either. Although I recommend literal notation, as it's more
                        flexible than an array in my humble opinion.

                        var array = [];
                        array["county"] = "counties";
                        array["house"] = "houses";
                        array["country"] = "countries" ;

                        One of the good things about arrays, is that you can use array.length
                        to obtain the number of items stored within it. Or beit, the highest
                        numbered key. This won't work when you use an array in an associative
                        manner as above, so I think objects are better, as I find them less
                        error prone, and easier to hand programatically .

                        Here's the same thing as literal notation:

                        var obj = {
                        country: "country",
                        house: "houses",
                        country: "countries"
                        }

                        You can access the values like so:

                        var result = obj.house; // result = "houses"

                        or like this:

                        var result = obj['county']; // result = "counties"

                        The latter is the safer way to do it, as it's a lot less error prone,
                        and gives you more control. As with arrays, you can use a variable
                        name for the key like so:

                        var key = "country";
                        var result = obj[key] // result = "countries"

                        You can also add methods to your object, which will be publicly
                        available from outside of the object, and put objects inside of
                        objects like this:
                        var mainObj = {
                        var obj = {
                        country: "country",
                        house: "houses",
                        country: "countries" ,
                        },
                        print: function() {
                        var output = "";
                        for (item in this.obj) {
                        output += key+" ="+this.obj[key]+"\n";
                        }
                        alert(output);
                        }
                        }

                        I hope this makes sense, and helps you out a little, and I also hope I
                        am not wasting both our time telling you things you already know. You
                        also need to remember to use the "this" keyword, to refer to any of
                        the properties or methods within the current object.

                        I am basically suggesting objects over arrays, but it really depends
                        on your needs more than anything. Objects are a lot more flexible, and
                        I believe they're also easier to work with. As you can easily
                        customise them and add methods to do all sorts of interesting and
                        useful things, they are well worth using.

                        Comment

                        • Navodit

                          #13
                          Re: case statements in Javascript


                          "Daz" <cutenfuzzy@gma il.comwrote in message
                          news:1176920007 .268678.179090@ q75g2000hsh.goo glegroups.com.. .
                          On Apr 18, 5:26 pm, "Navodit" <kaush...@uiuc. eduwrote:
                          >"Lee" <REM0VElbspamt. ..@cox.netwrote in message
                          >>
                          >news:f00e9k02a of@drn.newsguy. com...
                          >>
                          >>
                          >>
                          Lee said:
                          >>
                          >>Navodit said:
                          >>
                          >>>Thanks for all the feedback and comments. First of all I have not
                          >>>written
                          >>>those function names, my job is first to clean up the code as much as
                          >>>possible and then think about renaming. Each of those functions
                          >>>correspond s
                          >>>to around 50-100 lines of code so it is indeed useful to have them as
                          >>>separate functions. Each of those functions populates dropdown with
                          >>>counties
                          >>>for that particular state so when i say it doesnt work that implies
                          >>>the
                          >>>dropdown doesn't get populated when I use the case statement while it
                          >>>does
                          >>>get populated if the if statements are used.
                          >>
                          >>You haven't really made a case for separate functions.
                          >>If the functions differ only by what data they use, then
                          >>you should be using an array, rather than a switch.
                          >>
                          Or, in this case, maybe a data structure built on Objects.
                          Here's a simplified example of what I mean:
                          >>
                          <html>
                          <head>
                          <script type="text/javascript">
                          var stateData = {
                          IN: {
                          name: "Indiana",
                          capital: "Indianapol is",
                          counties: [ "Adams","Allen" ,"Bartholomew", "..." ]
                          },
                          IL: {
                          name: "Illinois",
                          capital: "Springfiel d",
                          counties: [ "Adams", "Alexander" , "Bond", "..." ]
                          },
                          KS: {
                          name: "Kansas",
                          capital: "Topeka",
                          counties: [ "Allen", "Anderson", "Atchison", "..." ]
                          }
                          }
                          >>
                          function populateState(s el) {
                          if(sel.selected Index) {
                          var stateInfo=state Data[sel.options[sel.selectedInd ex].text];
                          msg="State: "+stateInfo.nam e+"\n"
                          +"Capital: "+stateInfo.cap ital+"\n"
                          +"Counties:\ n";
                          for(var i=0;i<stateInfo .counties.lengt h;i++) {
                          msg+=" "+stateInfo.cou nties[i]+"\n";
                          }
                          alert(msg);
                          }
                          }
                          </script>
                          </head>
                          <body>
                          <form>
                          <select onchange="popul ateState(this)" >
                          <option>Choos e a State</option>
                          <option>IL</option><option> KS</option><option> IN</option>
                          </select>
                          </form>
                          </body>
                          </html>
                          >>
                          --
                          >>
                          >Thanks for the sample code. I think it does make more sense to use a data
                          >structure instead of using functions. However I have a doubt:
                          >>
                          >In my case, I am not hardcoding ' counties' as shown in the example above
                          >but I have stored it in an array 'county'. So when I am defining the data
                          >structure what is the best way to set 'counties' for a state say 'IL' to
                          >be
                          >equal to the array 'county'. Is it something like:
                          >>
                          >counties: county
                          >>
                          >or
                          >>
                          >counties = county
                          >>
                          >or something else?
                          >
                          You can do either. Although I recommend literal notation, as it's more
                          flexible than an array in my humble opinion.
                          >
                          var array = [];
                          array["county"] = "counties";
                          array["house"] = "houses";
                          array["country"] = "countries" ;
                          >
                          One of the good things about arrays, is that you can use array.length
                          to obtain the number of items stored within it. Or beit, the highest
                          numbered key. This won't work when you use an array in an associative
                          manner as above, so I think objects are better, as I find them less
                          error prone, and easier to hand programatically .
                          >
                          Here's the same thing as literal notation:
                          >
                          var obj = {
                          country: "country",
                          house: "houses",
                          country: "countries"
                          }
                          >
                          You can access the values like so:
                          >
                          var result = obj.house; // result = "houses"
                          >
                          or like this:
                          >
                          var result = obj['county']; // result = "counties"
                          >
                          The latter is the safer way to do it, as it's a lot less error prone,
                          and gives you more control. As with arrays, you can use a variable
                          name for the key like so:
                          >
                          var key = "country";
                          var result = obj[key] // result = "countries"
                          >
                          You can also add methods to your object, which will be publicly
                          available from outside of the object, and put objects inside of
                          objects like this:
                          var mainObj = {
                          var obj = {
                          country: "country",
                          house: "houses",
                          country: "countries" ,
                          },
                          print: function() {
                          var output = "";
                          for (item in this.obj) {
                          output += key+" ="+this.obj[key]+"\n";
                          }
                          alert(output);
                          }
                          }
                          >
                          I hope this makes sense, and helps you out a little, and I also hope I
                          am not wasting both our time telling you things you already know. You
                          also need to remember to use the "this" keyword, to refer to any of
                          the properties or methods within the current object.
                          >
                          I am basically suggesting objects over arrays, but it really depends
                          on your needs more than anything. Objects are a lot more flexible, and
                          I believe they're also easier to work with. As you can easily
                          customise them and add methods to do all sorts of interesting and
                          useful things, they are well worth using.
                          >
                          Thanks. All the stuff that you mentioned above was new to me so it was
                          helpful :)


                          Comment

                          • Daz

                            #14
                            Re: case statements in Javascript

                            On Apr 18, 9:43 pm, "Navodit" <kaush...@uiuc. eduwrote:
                            "Daz" <cutenfu...@gma il.comwrote in message
                            >
                            news:1176920007 .268678.179090@ q75g2000hsh.goo glegroups.com.. .
                            >
                            >
                            >
                            On Apr 18, 5:26 pm, "Navodit" <kaush...@uiuc. eduwrote:
                            "Lee" <REM0VElbspamt. ..@cox.netwrote in message
                            >
                            >news:f00e9k02a of@drn.newsguy. com...
                            >
                            Lee said:
                            >
                            >Navodit said:
                            >
                            >>Thanks for all the feedback and comments. First of all I have not
                            >>written
                            >>those function names, my job is first to clean up the code as much as
                            >>possible and then think about renaming. Each of those functions
                            >>corresponds
                            >>to around 50-100 lines of code so it is indeed useful to have them as
                            >>separate functions. Each of those functions populates dropdown with
                            >>counties
                            >>for that particular state so when i say it doesnt work that implies
                            >>the
                            >>dropdown doesn't get populated when I use the case statement while it
                            >>does
                            >>get populated if the if statements are used.
                            >
                            >You haven't really made a case for separate functions.
                            >If the functions differ only by what data they use, then
                            >you should be using an array, rather than a switch.
                            >
                            Or, in this case, maybe a data structure built on Objects.
                            Here's a simplified example of what I mean:
                            >
                            <html>
                            <head>
                            <script type="text/javascript">
                            var stateData = {
                            IN: {
                            name: "Indiana",
                            capital: "Indianapol is",
                            counties: [ "Adams","Allen" ,"Bartholomew", "..." ]
                            },
                            IL: {
                            name: "Illinois",
                            capital: "Springfiel d",
                            counties: [ "Adams", "Alexander" , "Bond", "..." ]
                            },
                            KS: {
                            name: "Kansas",
                            capital: "Topeka",
                            counties: [ "Allen", "Anderson", "Atchison", "..." ]
                            }
                            }
                            >
                            function populateState(s el) {
                            if(sel.selected Index) {
                            var stateInfo=state Data[sel.options[sel.selectedInd ex].text];
                            msg="State: "+stateInfo.nam e+"\n"
                            +"Capital: "+stateInfo.cap ital+"\n"
                            +"Counties:\ n";
                            for(var i=0;i<stateInfo .counties.lengt h;i++) {
                            msg+=" "+stateInfo.cou nties[i]+"\n";
                            }
                            alert(msg);
                            }
                            }
                            </script>
                            </head>
                            <body>
                            <form>
                            <select onchange="popul ateState(this)" >
                            <option>Choos e a State</option>
                            <option>IL</option><option> KS</option><option> IN</option>
                            </select>
                            </form>
                            </body>
                            </html>
                            >
                            --
                            >
                            Thanks for the sample code. I think it does make more sense to use a data
                            structure instead of using functions. However I have a doubt:
                            >
                            In my case, I am not hardcoding ' counties' as shown in the example above
                            but I have stored it in an array 'county'. So when I am defining the data
                            structure what is the best way to set 'counties' for a state say 'IL' to
                            be
                            equal to the array 'county'. Is it something like:
                            >
                            counties: county
                            >
                            or
                            >
                            counties = county
                            >
                            or something else?
                            >
                            You can do either. Although I recommend literal notation, as it's more
                            flexible than an array in my humble opinion.
                            >
                            var array = [];
                            array["county"] = "counties";
                            array["house"] = "houses";
                            array["country"] = "countries" ;
                            >
                            One of the good things about arrays, is that you can use array.length
                            to obtain the number of items stored within it. Or beit, the highest
                            numbered key. This won't work when you use an array in an associative
                            manner as above, so I think objects are better, as I find them less
                            error prone, and easier to hand programatically .
                            >
                            Here's the same thing as literal notation:
                            >
                            var obj = {
                            country: "country",
                            house: "houses",
                            country: "countries"
                            }
                            >
                            You can access the values like so:
                            >
                            var result = obj.house; // result = "houses"
                            >
                            or like this:
                            >
                            var result = obj['county']; // result = "counties"
                            >
                            The latter is the safer way to do it, as it's a lot less error prone,
                            and gives you more control. As with arrays, you can use a variable
                            name for the key like so:
                            >
                            var key = "country";
                            var result = obj[key] // result = "countries"
                            >
                            You can also add methods to your object, which will be publicly
                            available from outside of the object, and put objects inside of
                            objects like this:
                            var mainObj = {
                            var obj = {
                            country: "country",
                            house: "houses",
                            country: "countries" ,
                            },
                            print: function() {
                            var output = "";
                            for (item in this.obj) {
                            output += key+" ="+this.obj[key]+"\n";
                            }
                            alert(output);
                            }
                            }
                            >
                            I hope this makes sense, and helps you out a little, and I also hope I
                            am not wasting both our time telling you things you already know. You
                            also need to remember to use the "this" keyword, to refer to any of
                            the properties or methods within the current object.
                            >
                            I am basically suggesting objects over arrays, but it really depends
                            on your needs more than anything. Objects are a lot more flexible, and
                            I believe they're also easier to work with. As you can easily
                            customise them and add methods to do all sorts of interesting and
                            useful things, they are well worth using.
                            >
                            Thanks. All the stuff that you mentioned above was new to me so it was
                            helpful :)
                            My apologies. This example won't work:
                            var mainObj = {
                            var obj = {
                            country: "country",
                            house: "houses",
                            country: "countries" ,
                            },
                            print: function() {
                            var output = "";
                            for (item in this.obj) {
                            output += key+" ="+this.obj[key]+"\n";
                            }
                            alert(output);
                            }
                            }

                            It should have read:

                            var mainObj = {
                            obj: {
                            country: "country",
                            house: "houses",
                            country: "countries" ,
                            },
                            print: function() {
                            var output = "";
                            for (item in this.obj) {
                            output += key+" ="+this.obj[key]+"\n";
                            }
                            alert(output);
                            }

                            }

                            Comment

                            • Navodit

                              #15
                              Re: case statements in Javascript


                              "Daz" <cutenfuzzy@gma il.comwrote in message
                              news:1176935262 .536691.314960@ y80g2000hsf.goo glegroups.com.. .
                              On Apr 18, 9:43 pm, "Navodit" <kaush...@uiuc. eduwrote:
                              >"Daz" <cutenfu...@gma il.comwrote in message
                              >>
                              >news:117692000 7.268678.179090 @q75g2000hsh.go oglegroups.com. ..
                              >>
                              >>
                              >>
                              On Apr 18, 5:26 pm, "Navodit" <kaush...@uiuc. eduwrote:
                              >"Lee" <REM0VElbspamt. ..@cox.netwrote in message
                              >>
                              >>news:f00e9k02 aof@drn.newsguy .com...
                              >>
                              Lee said:
                              >>
                              >>Navodit said:
                              >>
                              >>>Thanks for all the feedback and comments. First of all I have not
                              >>>written
                              >>>those function names, my job is first to clean up the code as much
                              >>>as
                              >>>possible and then think about renaming. Each of those functions
                              >>>correspond s
                              >>>to around 50-100 lines of code so it is indeed useful to have them
                              >>>as
                              >>>separate functions. Each of those functions populates dropdown with
                              >>>counties
                              >>>for that particular state so when i say it doesnt work that implies
                              >>>the
                              >>>dropdown doesn't get populated when I use the case statement while
                              >>>it
                              >>>does
                              >>>get populated if the if statements are used.
                              >>
                              >>You haven't really made a case for separate functions.
                              >>If the functions differ only by what data they use, then
                              >>you should be using an array, rather than a switch.
                              >>
                              Or, in this case, maybe a data structure built on Objects.
                              Here's a simplified example of what I mean:
                              >>
                              <html>
                              <head>
                              <script type="text/javascript">
                              var stateData = {
                              IN: {
                              name: "Indiana",
                              capital: "Indianapol is",
                              counties: [ "Adams","Allen" ,"Bartholomew", "..." ]
                              },
                              IL: {
                              name: "Illinois",
                              capital: "Springfiel d",
                              counties: [ "Adams", "Alexander" , "Bond", "..." ]
                              },
                              KS: {
                              name: "Kansas",
                              capital: "Topeka",
                              counties: [ "Allen", "Anderson", "Atchison", "..." ]
                              }
                              }
                              >>
                              function populateState(s el) {
                              if(sel.selected Index) {
                              var stateInfo=state Data[sel.options[sel.selectedInd ex].text];
                              msg="State: "+stateInfo.nam e+"\n"
                              +"Capital: "+stateInfo.cap ital+"\n"
                              +"Counties:\ n";
                              for(var i=0;i<stateInfo .counties.lengt h;i++) {
                              msg+=" "+stateInfo.cou nties[i]+"\n";
                              }
                              alert(msg);
                              }
                              }
                              </script>
                              </head>
                              <body>
                              <form>
                              <select onchange="popul ateState(this)" >
                              <option>Choos e a State</option>
                              <option>IL</option><option> KS</option><option> IN</option>
                              </select>
                              </form>
                              </body>
                              </html>
                              >>
                              --
                              >>
                              >Thanks for the sample code. I think it does make more sense to use a
                              >data
                              >structure instead of using functions. However I have a doubt:
                              >>
                              >In my case, I am not hardcoding ' counties' as shown in the example
                              >above
                              >but I have stored it in an array 'county'. So when I am defining the
                              >data
                              >structure what is the best way to set 'counties' for a state say 'IL'
                              >to
                              >be
                              >equal to the array 'county'. Is it something like:
                              >>
                              >counties: county
                              >>
                              >or
                              >>
                              >counties = county
                              >>
                              >or something else?
                              >>
                              You can do either. Although I recommend literal notation, as it's more
                              flexible than an array in my humble opinion.
                              >>
                              var array = [];
                              array["county"] = "counties";
                              array["house"] = "houses";
                              array["country"] = "countries" ;
                              >>
                              One of the good things about arrays, is that you can use array.length
                              to obtain the number of items stored within it. Or beit, the highest
                              numbered key. This won't work when you use an array in an associative
                              manner as above, so I think objects are better, as I find them less
                              error prone, and easier to hand programatically .
                              >>
                              Here's the same thing as literal notation:
                              >>
                              var obj = {
                              country: "country",
                              house: "houses",
                              country: "countries"
                              }
                              >>
                              You can access the values like so:
                              >>
                              var result = obj.house; // result = "houses"
                              >>
                              or like this:
                              >>
                              var result = obj['county']; // result = "counties"
                              >>
                              The latter is the safer way to do it, as it's a lot less error prone,
                              and gives you more control. As with arrays, you can use a variable
                              name for the key like so:
                              >>
                              var key = "country";
                              var result = obj[key] // result = "countries"
                              >>
                              You can also add methods to your object, which will be publicly
                              available from outside of the object, and put objects inside of
                              objects like this:
                              var mainObj = {
                              var obj = {
                              country: "country",
                              house: "houses",
                              country: "countries" ,
                              },
                              print: function() {
                              var output = "";
                              for (item in this.obj) {
                              output += key+" ="+this.obj[key]+"\n";
                              }
                              alert(output);
                              }
                              }
                              >>
                              I hope this makes sense, and helps you out a little, and I also hope I
                              am not wasting both our time telling you things you already know. You
                              also need to remember to use the "this" keyword, to refer to any of
                              the properties or methods within the current object.
                              >>
                              I am basically suggesting objects over arrays, but it really depends
                              on your needs more than anything. Objects are a lot more flexible, and
                              I believe they're also easier to work with. As you can easily
                              customise them and add methods to do all sorts of interesting and
                              useful things, they are well worth using.
                              >>
                              >Thanks. All the stuff that you mentioned above was new to me so it was
                              >helpful :)
                              >
                              My apologies. This example won't work:
                              var mainObj = {
                              var obj = {
                              country: "country",
                              house: "houses",
                              country: "countries" ,
                              },
                              print: function() {
                              var output = "";
                              for (item in this.obj) {
                              output += key+" ="+this.obj[key]+"\n";
                              }
                              alert(output);
                              }
                              }
                              >
                              It should have read:
                              >
                              var mainObj = {
                              obj: {
                              country: "country",
                              house: "houses",
                              country: "countries" ,
                              },
                              print: function() {
                              var output = "";
                              for (item in this.obj) {
                              output += key+" ="+this.obj[key]+"\n";
                              }
                              alert(output);
                              }
                              >
                              }
                              >
                              An earlier implementation (which worked) read:


                              function InsuranceCounty ()
                              {
                              if (document.Insur ance.State.sele ctedIndex != 0)
                              {

                              document.Insura nce.county[0].value = "";
                              document.Insura nce.county[0].text = "Select County";
                              document.Insura nce.county[0].selected = true;

                              if (document.Insur ance.State.sele ctedIndex == 1)
                              {
                              ifIll();
                              }
                              }
                              else
                              document.Insura nce.State.reset ();
                              }

                              where:

                              function ifIll()
                              {
                              document.Insura nce.county.leng th = 103;

                              //Fetch data from server side
                              var countyId = document.dataho lder.illCountyI d.value;
                              var county = document.dataho lder.illCounty. value;

                              populateDropBox (countyId, county);
                              }

                              //similar functions for other states exist....

                              and the form is as follows:

                              <select type="TEXT" name="State" onChange="Insur anceCounty()">
                              <OPTION VALUE="0">Selec t State
                              <OPTION VALUE="17">Illi nois
                              <OPTION VALUE="20">Kans as
                              </select>

                              Now instead of using the functions I am trying to use a data structure:

                              function InsuranceCounty ()
                              {
                              if (document.Insur ance.State.sele ctedIndex != 0)
                              {

                              document.Insura nce.county[0].value = "";
                              document.Insura nce.county[0].text = "Select County";
                              document.Insura nce.county[0].selected = true;

                              //var state = document.Insura nce.State;
                              test();
                              }
                              else
                              document.Insura nce.State.reset ()
                              }

                              function test()
                              {
                              var stateData = {
                              Illinois: {
                              size = 103,
                              countyId= document.dataho lder.illCountyI d.value,
                              county= document.dataho lder.illCounty. value
                              },
                              Kansas: {
                              size = 106,
                              countyId= document.dataho lder.kanCountyI d.value,
                              county= document.dataho lder.kanCounty. value
                              }
                              }
                              document.Insura nce.county.leng th =
                              document.Insura nce.State.optio ns[document.Insura nce.State.selec tedIndex].text].size;
                              populateDropBox (stateData[document.Insura nce.State.optio ns[document.Insura nce.State.selec tedIndex].text].countyId,
                              stateData[document.Insura nce.State.optio ns[document.Insura nce.State.selec tedIndex].text].county);
                              }


                              This code doesnt work as in the dropdown for counties does not show the list
                              of counties for a state. Any idea what I might be missing here?



                              Comment

                              Working...