-1

I have this array that was returned by json.

{1:Android, 2:IOS, 3:Business Management Systems, 4:Database, 5:Codes/Scripts, 6:Others}

or

1: "Android"
2: "IOS"
3: "Business Management Systems"
4: "Database"
5: "Codes/Scripts"
6: "Others"

This array is saved on a variable data. And my current code of ajax is:

$.post('fetchSubCategory',{val:val},function(data){
            var subCategory = $.map(data, function(el){
                return el;
            });
             $.each(subCategory, function(key, value) {   
                 $('#subCategory')
                    .find('option')
                    .remove()
                    .end()
                    .append($('<option>', { value : key })
                    .text(value)); 
            });
      });

But it returns this [object Object]. I want this array to populate my select element that the values are those ids and the texts are those names. Something to be like this:

<select class="form-control square" id="subCategory" name="Category">
    <option value="1">Android</option>
    <option value="2">IOS</option>
    <option value="3">Business Management Systems</option>
    <option value="4">Database</option>
    <option value="5">Codes/Scripts</option>
    <option value="5">Others</option>
</select>

How could I achieve this on Javascript or jquery.

Jay Marz
  • 1,861
  • 10
  • 34
  • 54

1 Answers1

1

Concept Verification

The following will append option element to an existing #subCategory select element:

$.post('fetchSubCategory',{val:val},function(data){
    $.each(data, function(key, value) {   
        $('#subCategory').append(
            $('<option/>').val( key ).text( value )
        );
    });
});
PeterKA
  • 24,158
  • 5
  • 26
  • 48
  • same thing happened sir. still returns `[object Object]` and not the actual array. – Jay Marz Aug 11 '14 at 18:21
  • Please print out the result of `console.log( data )`. – PeterKA Aug 11 '14 at 18:22
  • this is the log of the `data` `0: {7:Graphic Design, 8:Portraits, 9:Photographs, 10:Compositions, 11:Paintings, 12:3D Modeling/Design, 13:Others}` – Jay Marz Aug 11 '14 at 18:26
  • What about `console.log( data[0].7 )` or `console.log( data[0]['7'] )`? – PeterKA Aug 11 '14 at 18:30
  • I spotted the glitch sir. Not on `ajax` side but on my `php`. I have returned the json value like this `return json([$array]);` that's why it logs with `0:` before the real array. So I removed that `[]` to look like this `return json($array);` then I used this code and it works. Thank you. – Jay Marz Aug 11 '14 at 18:40