0

Since whole afternoon I am trying to send some JSON response and capture them as select options. I have tried formatting JSON string in various ways to get it retrieved via nested each() function of jQuery but could not get it right.

Right now my code looks like this:

Current JSON String Format:

 {
  "person1" : {"id":1, "name":"name1", "dob":"01-Jan-2016"},
  "person2" : {"id":2, "name":"name2", "dob":"02-Jan-2016"},
  "person3" : {"id":3, "name":"name3", "dob":"03-Jan-2016"},
  "person4" : {"id":4, "name":"name4", "dob":"04-Jan-2016"}
 }

I had also tried this format:

{
"persons" : [
    {"id":1, "name":"name1", "dob":"01-Jan-2016"},
    {"id":2, "name":"name2", "dob":"02-Jan-2016"},
    {"id":3, "name":"name3", "dob":"03-Jan-2016"},
    {"id":4, "name":"name4", "dob":"04-Jan-2016"}
  ]
}

JQuery $.get().done() Handler:

var selectList = $("#personList");
var result = JSON.parse(data);
$.each(result, function(){
     $.each(this, function(key, value){
          alert(key + '=' + value);
          selectList.append($("<options />").val(name).text(value));
     });
 });

Now in the alert boxes I can get all the key and value pair, but I want the <option>'s value to be filled up by person.id and text by person.name. Which is not happening.

May be my JSON array string format is itself not correct.

Can anyone please help me out with these two piece of codes?

1 Answer 1

1

Using the current JSON format, in the outer $.each(), this references the person object, e.g. {"id":4, "name":"name4", "dob":"04-Jan-2016"}, so you just need to access its properties:

 $.each(result, function(){
   selectList.append($("<option />").val(this.id).text(this.name));
 });

Alternatively, it is passed as the second parameter, like how had it in the inner $.each, so you can do this:

 $.each(result, function(key, value){
    selectList.append($("<option />").val(value.id).text(value.name));
 });

By the way, the tag is <option> not <options>.

Sign up to request clarification or add additional context in comments.

3 Comments

Wow!! seems like you made my day!! :) Although my current JSON string format is good enough or the earlier one was better?? For now, I am getting the proper <option> tags with only one each() as you mentioned above.
Depends if you want to return other data in the JSON response. If not, the current format is smaller, so better
Thank you for prompt answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.