zohaib siddiqui
zohaib siddiqui

Reputation: 129

Populate one Dropdown on change of another dropdown using jQuery from database

I am newbie in Java Servlets. I have 2 dropdowns, say A and B, and I have this situation where if dropdown A changes, without reloading the page, dropdown B fills or populates data from the database.

I have seen a solution here in which it is said that this can be done by using jQuery. This is URL for doing this How to generate dynamic drop down lists using jQuery and jsp?

I wrote a json string on the response stream but when I check the values returned from it by using alert(options); it is returning null. but when it write response.getWriter().write(json);json has got values not empty I don't know what to do.

Upvotes: 1

Views: 5402

Answers (2)

Rasal Shukla
Rasal Shukla

Reputation: 121

function CallBack(data) {
        var obj = data;
        var id = "";
        var value = "";
        $.each(data,
            function (index, item) {
                id = item.Id;
                value = item.Value;
                $('#ProductId')
               .append($("<option></option>")
               .attr("value", id)
               .text(value));
            }
        );
    }

Upvotes: 2

dku.rajkumar
dku.rajkumar

Reputation: 18578

I am not exactly sure about your code but you can do something like :

$('#drop_down_1_id').change(function(){
var drop_down_1_value = $(this).options[$('#drop_down_1_id').selectedIndex];
$.ajax({
  type: 'GET',
  url : 'url',
  data : 'value='+drop_down_1_value,
  dataType : 'json',
  success: function(data){
    $('#drop_down_2_id').html('');
    $(data).each(function(value){
      $('#drop_down_2_id').append('<option value="'+value+'">'+value+'</option>');
    }); // you can change this loop as per your response data type
  }
});
});

Upvotes: 1

Related Questions