Question

This is my data being returned from ajax call (EDIT: json format now):

[{"PROCEDURE_ID":362183,"PROCEDURE_NAME":"Biopsy, Breast; Lumpectomy"}, {"PROCEDURE_ID":558975,"PROCEDURE_NAME":"Biopsy, Cervix"},{"PROCEDURE_ID":558977,"PROCEDURE_NAME":"Biopsy, intrauterine"},{"PROCEDURE_ID":558976,"PROCEDURE_NAME":"Biopsy, Libial"}]

I am trying to put this in a select drop down and no matter what I do, it fails, either select-options are undefined or jquery throw error.
This is what I have tried so far 2 different methods (selField is dynamic element)

success: function(json){

         if (json != '' )
            var vx='<option value="">All</option>';
               $.each (json.DATA, function(k, v){

                   vx+='<option value="'+k.Procedure_ID+'">'+v.Procedure_Name+'</option>';
               });
               $(selField).html(vx);
               }
Was it helpful?

Solution

There are a couple of things wrong that I see from the code you posted. First, as Scott Stroz mentioned, you are referencing the JSON data in your .each loop using camel case but the JSON data actually has it in all UPPER case. JavaScript is case sensitive so that needs to match. Secondly, you are referencing PROCEDURE_ID using the wrong argument in your .each loop. The first argument of the function (k in your code) is the loop index. The second argument (v in your code) is the element data. So you need to reference both PROCEDURE_ID and PROCEDURE_NAME using the v argument like so:

vx+='<option value="'+v.PROCEDURE_ID+'">'+v.PROCEDURE_NAME+'</option>';

From the comments it also appears that you were not parsing the JSON response either. That would keep the .each loop from iterating. You can do so by using either JSON.parse() or by defining the dataType of your AJAX call to be 'json' assuming that it is properly formatted.

I created a simple jsFiddle to show you how the .each iteration of your JSON object should work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top