views:

586

answers:

3

I am new to Javascript, JSON and jQuery. So please be easy on me. I have a JSP page that contain a drop down list. The contents of the drop down list are populated when the page is loaded. I wrote a Servlet that return the contain of the drop down list in the form of Map, and convert it to JSON string and sent back to the jsp via response.getWriter().write(json); However I am having trouble to getting the result back from the jsp side, and populate the contain of the drop down list from the result. Here are my codes

customer.jsp

    $(document).ready(function(){  
          getCustomerOption('customer');//try to pre-populate the customer drop down list
    });  
    function getCustomerOption(ddId){
          var dd = $('#' + ddId);
          $.getJSON("http://localhost:8080/WebApps/DDListJASON", function(opts) {
                 $('>option', dd).remove(); // Remove all the previous option of the drop down
                 if(opts){
                     $.each(opts, function(key, value){
                          dd.append($('<option/>').val(key).text(value));
                     }
                 }
          });
    }

down where the drop down list is generated

<select id="customer" name="customer">  
<option></option>  
</select>  

The result is nothing get populated into the list. So sad

A: 

You may add additional <option> elements to a <select> with the code:

$("#selectID").append("<option>" + text + "</option>");

see: JQuery Docs

Kivin
+4  A: 

I think you are invoking the wrong function in document ready

Shouldn't it be

getInitialOption('customer');

instead of

getCustomerOption('customer');
rahul
I may be the stupidest kid in this world
Harry Pham
A: 

I don't understand $(''), but I'm not sure that's the problem either, hard to tell exactly.

I do know it will be quicker if you do create the list of options in-memory and then do one append with .html(options) rather than append them one at a time. That may make it easier to understand also, to build the html up one line at a time and then append it.

Devin Ceartas