0

I tried searching for my question in SO and found most of the answers for .Net and not for Java. So asking this question again.

How to create a cascading dropdown in JSP? i.e the values of the second dropdown box should depend on the first one. These values should be fetched from the database. I know that I should use AJAX, but I have no idea about how to do it. If someone can help it would be of much help.

rgksugan
  • 3,521
  • 12
  • 45
  • 53

1 Answers1

1

You need to download JQuery (JavaScript framework) and include that in the head section of the HTML.

<script type="text/javascript" src=PathToJquery.js></script>

Inside the OnChange function for first dropdown call the function to populate the subsequent dropdowns. $(document).ready(function() { $('#DDIdParent').change(function() { populateChildDropdown('DDIdParent'); }); });

The function is a s follows:

function populateChildDropdown(ddId) {
            var dd = $('#' + ddId);
            $.getJSON('json/mapping?dd=' + ddId, function(opts) {
                $('>option', dd).remove(); // Clear old options first.
                if (opts) {
                    $.each(opts, function(key, value) {
                        dd.append($('<option/>').val(key).text(value));
                    });
                } else {
                    dd.append($('<option/>').text("Please select the parent DD"));
                }
            });
        }

Inside your Servlet's doGet method, you will have a code like this to get the value of subsequent dropdown from the database as a JSON String:

        Map options = yourDao.callDatabase(parameter);
        String json = new Gson().toJson(options);
        res.setContentType("application/json");
        res.setCharacterEncoding("UTF-8");
        res.getWriter().write(json);

You need to map the json/mapping to your servlet inside web.xml. You can also pass parameters from the jquery function if needed.

Piyush Mattoo
  • 15,454
  • 6
  • 47
  • 56