Chris Olson
Chris Olson

Reputation: 1041

JSON into Options of a Input Select

I have a string of json that I'm trying to put into the options of my select input field. I'd like the Type_label to go in the Type_lable and the value to be the type number.

Here is my json:

var serviceCODES = [{
"type_label": "Medical Care",
"type": "1",

}, {
"type_label": "Surgical",
"type": "2",

}, {
"type_label": "Consultation",
"type": "3",

}]

Here is my html and js

 <select id="datas" name="datas" >

 <script>
    var $select = $('#datas');

    $.each(serviceCODES, function(i, val){
        $select.append($('<option />', { value: (i+1), text: val[i+1] }));
     });
 </script>

For some reason this isn't working. Any help would be much appreciated.

Thanks!

Upvotes: 1

Views: 75

Answers (2)

soulcheck
soulcheck

Reputation: 36777

Try:

$.each(serviceCODES, function(i, val){
    $select.append($('<option />', { value: (i+1), text: val.type_label}));
});

$.each() passes current index and item to the callback function. You tried to access elements of val by index. Also you probably want to access some property of val.

Upvotes: 1

DontVoteMeDown
DontVoteMeDown

Reputation: 21465

Try this:

$select.append('<option value="' + i + '">' + val.type_label + '</option>');

In those cases, when you're confusing of how retrieve data in a loop, always take a look on arguments provided by the function(I always use this):

console.log(arguments);

Upvotes: 2

Related Questions