JSP drop down list question

drop-down-menujsp

I would like to ask a question

I want to show 3 drop down list in one JSP page,

where the the second drop down list is based on the selected value in the 1st drop down list,

and so on…

According to my limited knowledge, when user selects a value from drop down list,

the user needs to click a button to pass the value to server side.

like this:

<form action="second_drop.jsp">
   <select name="drop">
    ...
   </select>
   <input type="submit" value="Submit" />
</form>

Now, I would like to ask a question,

is it possible to pass the drop down list value without clicking button?

that is, when users select a value from drop down list,

the selected value can be automatically passed to server side without clicking submit button.

then the server will based on the selected value to display the second drop down list

thanks for help.

Best Answer

It is absolutely possible to do this using the mystical power of ajax! This particular behavior you're looking for is called "chained dropdowns" or "dependent dropdowns." Here's how I'd do it with jQuery, heavily commented so it's (hopefully) clear:

Markup

<form action="second_drop.jsp">
   <select id="first_drop" name="drop">
    ...
   </select>
   <select id="second_drop" disabled="disabled"></select>
   <input type="submit" value="Submit" />
</form>

JavaScript

$(function () // run the following code when the DOM is ready
{
    $('#first_drop') // equivalent to document.getElementById('first_drop')
        .change(function () // run the following code whenever the DDL value changes
        {
            var val = $(this).val(); // get the new value of the first DDL
            $('#second_drop').load(
              'second_drop.jsp', // this is the URL to load
              {drop: val} // pass this data to the server with the request
              function () // execute this function when the response comes back
              {
                  $('#this').attr('disabled', false); // enable the 2nd DDL
              });
        });
});

second_drop.jsp should respond with a list of <option>s:

<option value="val1">Option 1</option>
<option value="val2">Option 2</option>
<option value="val3">Option 3</option>

There's a lot there, if you're not familiar with JavaScript and/or jQuery, so just ask if there's anything you don't understand.

jQuery functions used