WhoAmI
WhoAmI

Reputation: 57

JSON Array Iteration

Here is my json output which i am creating from my spring controller.

[{"id":"1","name":"albert"},{"id":"2","name":"john"},{"id":"3","name":"mac-millon"},{"id":"4","name":"stenberg"},{"id":"5","name":"almaria"}]

In my jsp file , am iterating the json array as below

success: function(data){
     var content= JSON.parse(data);
     $.each(content, function(i, data) {
                            $('#selectBox').append($('<option>').text(data.name).attr('value',data.id ));
                    });

but it always displaying only the last value in my select box

id="5" value="almaria"

Is there anything wrong in my iteration? or i should create the json output in different format? Please help.

Upvotes: 0

Views: 61

Answers (2)

JHS
JHS

Reputation: 1428

FYI you should not need to call JSON.parse if your headers are set correctly in the response. (Content-Type: application/json).

Your code seems to work fine in this example despite the duplicate IDs. See that all 5 options appear when the select box is clicked. There is also the multiple HTML attribute which might do what you want.

var content = [{"id":"2","name":"albert"},{"id":"2","name":"john"},{"id":"3","name":"mac-millon"},{"id":"4","name":"stenberg"},{"id":"5","name":"almaria"}];

//var content= JSON.parse(data);

$(document).ready(function() {
  $.each(content, function(i, data) {
     $('#selectBox, #selectBoxMulti').append($('<option>').text(data.name).attr('value',data.id ));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="selectBox">
</select>

<select id="selectBoxMulti" multiple>
</select>

Upvotes: 1

Martin
Martin

Reputation: 13

One thing I see is your JSON has 2 id: 2 {"id":"2","name":"albert"},{"id":"2","name":"john"}

Not sure if that is the desired logic.

Upvotes: 0

Related Questions