dynamic menus with jsp only (no javascript)

Discussions

Web tier: servlets, JSP, Web frameworks: dynamic menus with jsp only (no javascript)

  1. dynamic menus with jsp only (no javascript) (1 messages)

    Hi,

    I was wondering if it is possible to dynamically update select statements on a web page without using javascript. For instance, suppose you have two drop down select menus, and you want to update the options in the second select based on the value chosen in the first.

    I have managed to do this using javascript, but my current project requires database calls to populate the drop-down menus, which I have handled with jsp/javabeans. Passing variables between jsp and javascript seems messy - lots of hacking and passing variables through the url. I would like to avoid mixing the code and just use java for the whole thing.

    Any ideas?

    Thanks,
    Geoff
  2. One way I've seen this implemented is by using dynamically created javascript arrays. I realize you said you prefer not to use javascript at all (I tend to agree)) but there can be situations that efficient use of it prevents server requests and thus increases overall performance.

    What you can do is create arrays of the second menu choices with java and store then in the page as javascript arrays upon first load. When a selection is made in the first drop down, set the appropriate array as the second menu's options. While this solution is not pure java, it does prevent nasty urls and essentially uses javascript for what its intended; simple, client side manipulation.

    I'm don't have any sample code to post here but I can point you www.carsdirect.com which atleast shows the necessary javascript. The java's simple - you just need to generate the array code similar to:

    MenuOneOptions[0]='option 1';
    MenuTwoOptions[0]='choice based on option 1, another choice based on option 1';
    MenuOneOptions[1]='option 2';
    MenuTwoOptions[1]='choice based on option 2, another choice based on option 2';

    I think this would do the trick. Haven't really tested it but it shows the general idea:

    <pre>
    String[] firstChoiceArray = { "option 1", "option 2" };
    for (int i=0; i< firstChoiceArray.length; i++) {
      System.out.println("MenuOneOptions[" + i + "] = '" + firstChoiceArray[i] + "';");

      // This array would be constructed from a sql result based on
      // firstChoiceArray[i]
      String[] secondChoiceArray = {
        "option based on choice " + i,
        "another option based on choice " + i };

      System.out.print("MenuTwoOptions[" + i + "] = 'Select an option");
      for (int j=0; j<secondChoiceArray.length; j++) {
        System.out.print("," + secondChoiceArray[j]);
      }
      System.out.println("';");
    }
    </pre>

    Good luck,

    andrew