How to create dynamic dropdowns using jQuery and jsp?

I have a list of types A in which each element contains a different list of type B. I want to create a form in which when the user selects a value from the drop-down list containing the values โ€‹โ€‹of A, the other is reduced to fill the values โ€‹โ€‹based on the selected list of elements of type B. I am new to jQuery, but I know that it is convenient to do this using jQuery, and not from pure jsp. Please give me a rough outline of the steps I need to follow to do this.

+5
jquery jsp
source share
2 answers

JSP is just server side view technology. It does not compete with jQuery. You can perfectly use JSP for this. But I understand that you want to run an asynchronous request using ajaxial methods, not a synchronous request. This is also not a problem in JSP.

First, we need to have two dropdown menus in the JSP:

<select id="dropdown1"> <c:forEach items="#{bean.items}" var="item"> <option value="#{item.value}">#{item.label}</option> </c:forEach> </select> <select id="dropdown2"> <option>Please select dropdown1</option> </select> 

Then we need to attach some jQuery to the change event so that it populates the second drop-down menu based on the value of the 1st drop-down list. Add the following to <script> in the JSP or an external script that loads through <script src> in the JSP:

 $(document).ready(function() { $('#dropdown1').change(function() { var selectedValue = $(this).val(); var servletUrl = 'dropdown2options?value=' + selectedValue; $.getJSON(servletUrl, function(options) { var dropdown2 = $('#dropdown2'); $('>option', dropdown2).remove(); // Clean old options first. if (options) { $.each(opts, function(key, value) { dropdown2.append($('<option/>').val(key).text(value)); }); } else { dropdown2.append($('<option/>').text("Please select dropdown1")); } }); }); }); 

In the servlet for url-pattern of /dropdown2options just return the parameter map as JSON . You can use gson for this.

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String selectedValue = request.getParameter("value"); Map<String, String> options = optionDAO.find(selectedValue); String json = new Gson().toJson(options); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(json); } 

That is basically all.

+10
source share

I answered a similar question about chain selectors here ... I don't know about jsp, but this version of jQuery should give you an idea.

0
source share

All Articles