There's a class 'Car' with brand and model as properties. I have a list of items of this class List<Car> myCars
. I need to represent 2 dropdowns in a JSP page, one for brand and another for model, that when you select the brand, in the model list only appear the ones from that brand. I don't know how to do this in a dynamic way.
Any suggestion on where to start?
Update
Ok, what I do now is send in the request a list with all the brand names, and a list of the items. The JS开发者_如何学CP code is like:
<select name="manufacturer" id="id_manufacturer" onchange="return getManufacturer();">
<option value=""></option>
<c:forEach items="${manufacturers}" var="man">
<option value="${man}" >${man}</option>
</c:forEach>
</select>
<select name="model" id="id_model">
<c:forEach items="${mycars}" var="car">
<c:if test="${car.manufacturer eq man_selected}">
<option value="${car.id}">${car.model}</option>
</c:if>
</c:forEach>
</select>
<script>
function getManufacturer()
{
man_selected = document.getElementById('id_manufacturer').value;
}
</script>
How do I do to refresh the 'model' select options according to the selected 'man_selected' ?
There are basically 3 ways to achieve this:
Use JavaScript to submit the form to the server side on change of the dropdown and let the JSP/Servlet load and display the child dropdown accordingly based on the request parameter. Technically the simplest way, but also the least user friendly way. You probably also want to revive all other input values of the form.
Let JSP populate the values in a JavaScript array and use a JavaScript function to load and display the child dropdown. A little bit trickier, certainly if you don't know JavaScript yet, but this is more user friendly. Only caveat is that this is bandwidth and memory inefficient when you have relatively a lot of dropdown items.
Let JavaScript fire an asynchronous HTTP request to the server side and display the child dropdown accordingly. Combines the best of options 1 and 2. Efficient and user friendly.
I've posted an extended answer with code samples here: Populating child dropdownlists in JSP/Servlet.
精彩评论