HungryProgrammer
HungryProgrammer

Reputation: 165

How to populate second dropdown in $.ajax() depending on value of first dropdown?

I have two dropdowns to fill up by applying the following cases:

  1. Fill the the first dropdown with all the folder names (done by using File class).
  2. Fill the second dropdown with the subfolder names which is now based on the first dropdown.

So my jQuery part is:

$('#rootFolder').change(function() { 
    var rootFoldervalue = $(this).options[$('#rootFolder').selectedIndex];

How do I send this selected rootFolder value to my JSP page so that i can again calculate the subFolder names and show it in the second dropdown?

getsubfolder.jsp

<%
    String root = request.getParameter("foldername");
    String path = "G:\\ANDROID\\";
    File rootFile = new File(path);
    File[] listOfDirs = rootFile.listFiles();
    out.println(listOfDirs);
%>

jQuery part:

$(document).ready(function() {
    $("#rootFolder").change(function() {
        var rootFolderValue = $('#rootFolder').val();
        $.ajax({
            url: 'getsubfolder.jsp',
            data:'foldername=' + rootFolderValue,
            dataType: 'json',
            success:function(data) {
                $.each(data, function(i, data) {
                $('#subFolder').append(
                    $('<option></option>').val(data.Value).html(data.Text)
                )});
            }
        });

Transferring file array as a JSON is not working. How do I manipulate the values received in the data of success part of $.ajax() to populate my second dropdown?

Upvotes: 1

Views: 2792

Answers (1)

JB Nizet
JB Nizet

Reputation: 691635

Your JS code could be simplified to

var rootFolderValue = $(this).val();

Once you have this value, send an AJAX request to your server (something like .../getSubFolders?rootFolder=<the root folder>). The server could answer with a JSON array of subfolders, or directly with the HTML to put inside the second select box. In the callback function of your AJAX request, populate the second select box with what you received from the server.

See http://api.jquery.com/category/ajax/. Depending on the strategy you choose, you might use get(), getJSON() or even load().

Upvotes: 1

Related Questions