Question

I have the following script:

$(function () {
    var selectValues = new Array();
    selectValues = [{"Selected":false,"Text":"Apple","Value":"1"},{"Selected":false,"Text":"Samsung","Value":"2"},{"Selected":false,"Text":"LG","Value":"3"}];
    $.each(selectValues, function (key, value) {
        $('#brand-0')
             .append($('<option>', { value: key })
             .text(value))
             .prop("selectedIndex", -1);
    });
    });

But when it runs, it displays each list object as [object Object]. What am I missing?

Was it helpful?

Solution

As I noted above, you have an array of objects, so each value in the .each() loop is the current object. You need to extract the data appropriate for each placement in the new option element.

$(function () {
    var selectValues = [{"Selected":false, "Text":"Apple",  "Value":"1"},
                        {"Selected":false, "Text":"Samsung","Value":"2"},
                        {"Selected":false, "Text":"LG",     "Value":"3"}];
    var brand = $('#brand-0');

    brand[0].selectedIndex = -1;

    $.each(selectValues, function (i, value) {
        $('<option>', { 
             value: value.Value,
             text: value.Text
        }).appendTo(brand);

        if (value.Selected) {
            brand[0].selectedIndex = i;
        }
    });
});

And by the way, you don't need all those double quotes in the selectedValues objects.

var selectValues = [{Selected:false, Text:"Apple",  Value:"1"},
                    {Selected:false, Text:"Samsung",Value:"2"},
                    {Selected:false, Text:"LG",     Value:"3"}];

OTHER TIPS

In your each loop, the parameter value contains one element of you array : {"Selected":false,"Text":"Apple","Value":"1"} for example.

Your need to specify which key of you object you want to display, otherwise you will display the whole object, which shows [object Object]

$(function () {
    var selectValues = new Array();
    selectValues = [{"Selected":false,"Text":"Apple","Value":"1"},{"Selected":false,"Text":"Samsung","Value":"2"},{"Selected":false,"Text":"LG","Value":"3"}];
    $.each(selectValues, function (key, value) {
    $('#brand-0')
        .append($('<option>', { value: value.key })
        .text(value.text))
        .prop("selectedIndex", -1);
    });
});

Handling object should be like this

$.each(selectValues, function (key, value) {
        $('#brand-0')
             .append($('<option>', { value:value.Value })
             .text(value.Text))
             .prop("selectedIndex", value.SelectedIndex);
    });

use example demo:

Fiddle

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