JSP drop down list – using selected item

drop-down-menujspjstlmodel-view-controllerservlets

I have a drop down list and a form with a few textboxes. I would like to populate this form with details of selected item in the drop down list.

I'm doing this in java MVC app (or wannabe) and I have in my jsp page something like this:

<select name="item">
            <c:forEach items="${persons}" var="selectedPerson">
                <c:set var="person" value="${selectedPerson}" />
                <option value="$selectedPerson.id">${selectedPerson.LastName}</option>
            </c:forEach>
</select> 

Persons is a list of the Person class.

I wonder is it possible to use the variable 'person' directly to fill the form, for example:

<textarea   name="name"  rows="1" cols="34" >
    ${selectedPerson.Name}
</textarea>

so that the rest of the form updates when the selectedPerson is changed?

I know how to do this within c#, but I don't have experience with java technologies.

Is it necessary to submit the form to servlet to do this, or it can be done on the client, since I have all my data in the persons list, from the moment of populating the drop down list?

Best Answer

The ${} syntax is JSP syntax, which will only be parsed and run once on the server to generate the HTML, and then sent down the wire as HTML. The changes to the select list then just happen in the client browser: the server doesn't know anything about them.

What you want to do is register a javascript listener on the select box. You should look into using a library ideally to help you do this. JQuery is a very popular solution and is worth reading up on if you're going to be doing this type of development.

If you end up using JQuery, you'll want to do something like the following

<select id="item" name="item">
        <c:forEach items="${persons}" var="selectedPerson">
            <c:set var="person" value="${selectedPerson}" />
            <option value="$selectedPerson.id">${selectedPerson.LastName}</option>
        </c:forEach>
</select>
<input name="lastName" id="lastName" type="text"/>

<script type="text/javascript">
    $(function() {
        $("#item").change(function() {
            $("#lastName").val($("option:selected", this).text());
        });
    });
</script>

This will make more sense once you've read a basic JQuery tutorial, but basically what it does is that each time the select list changes value, it gets the selected option and sets it's content to the lastName input field. Hope this helps.

Related Topic