DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 2 of 2
  1. #1
    Bob Guest

    Setting an option in an option element using a Java bean

    How can a particular option in an option element on a JSP be set using a getXXX()
    method of a Java bean?

  2. #2
    Larne Pekowsky Guest

    Re: Setting an option in an option element using a Java bean

    Bob <robert.byrnes@transcore.com> wrote:
    >How can a particular option in an option element on a JSP be set
    >using a getXXX() method of a Java bean?

    Unfortunately there's no easy, single-tag, sort of thing that will do
    this for you. You have to check each of your options, and when you
    find the currently chosen option add a SELECTED parameter. Something
    like this:

    <jsp:useBean class="ColorBean" id="which"/>

    <select name="color">
    <option <%= which.getColor().equals("Red") ? "SELECTED" : "" %>>Red
    <option <%= which.getColor().equals("Green") ? "SELECTED" : "" %>>Green
    <option <%= which.getColor().equals("Blue") ? "SELECTED" : "" %>>Blue

    The stuff in the expression tags <%= %> are little chunks of Java
    code. In Java something like

    expression1 ? expression2 : expression3

    means "If expression1 is true use expression2, otherwise use
    expression3." So the first clause:

    which.getColor().equals("Red") ? "SELECTED" : ""

    means "call getColor() on the 'which' bean, if it is equal to "Red"
    then add "SELECTED" to the page, otherwise add an empty string. So if
    which.getColor() is Red, this will result in:

    <option SELECTED>Red

    which is exactly what we want.

    Admittedly this is a little verbose, and requires a fair bit of
    repeated code. I think it should be possible to create a custom tag
    or two that would hide some of this complexity, but I haven't seen any
    examples yet.

    - Larne

Similar Threads

  1. Replies: 0
    Last Post: 02-20-2005, 01:06 PM
  2. Replies: 0
    Last Post: 02-21-2002, 01:41 PM
  3. Setting a Cookie from a Java Servlet
    By Jose Rodz in forum Java
    Replies: 2
    Last Post: 02-13-2002, 11:36 AM
  4. setting Option Value
    By Donnie in forum ASP.NET
    Replies: 2
    Last Post: 10-19-2000, 09:25 AM
  5. Replies: 0
    Last Post: 09-01-2000, 07:56 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center
Latest Articles
Questions? Contact us.
Web Development
Latest Tips
Open Source

   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center

We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.