how to bind a simple json object to a dropdown in knockout?

2,245 views
Skip to first unread message

yahya...@gmail.com

unread,
May 23, 2013, 2:03:13 PM5/23/13
to knock...@googlegroups.com

I have a simple json object:

“{"MediaType":1,"Country":2,"Region":3,"SubRegion":4}"

I want to bind it to a drop down so that the resulting html would look like the following. I don't know how to do this as the JSON represents different name and value or better put it is a representation of key value pairs.

<option value="1">Media Type</option>
<option value="2">Country</option>
<option value="3">Region</option>
<option value="4">Sub Region</option>
Message has been deleted

davo...@gmail.com

unread,
May 25, 2013, 2:31:12 AM5/25/13
to knock...@googlegroups.com, yahya...@gmail.com
Hi,

you can do something like this:

Javasctipt code
ko.applyBindings({
    selectOptions
: [
       
{ selectName: "MediaType", selectValue: 1 },
       
{ selectName: "Country", selectValue: 2 },
       
{ selectName: "Region", selectValue: 3 },
       
{ selectName: "SubRegion", selectValue: 4 }
   
]
});

And in html
<select data-bind="foreach: selectOptions">
   
<option data-bind="text: selectName, value: selectValue"></option>
</select>

You can see the result at: http://jsfiddle.net/zLCvz/4/

Patrick Steele

unread,
May 25, 2013, 9:37:45 AM5/25/13
to knock...@googlegroups.com
You could use a little javascript to iterate over the properties of your json object and create an array of items that you then bind to your <select> tag.  Something like this:

var json = {
    'MediaType': 1,

    'Country': 2,
    'Region': 3,
    'SubRegion': 4
};

var ViewModel = function(js) {
    var self = this;
   
    self.json = js;
    self.options = ko.computed(function() {
        var opts = [];
        for(var key in json)
        {
            if(json.hasOwnProperty(key))
            {
                opts.push({name: key, value: json[key]});
            }
        }
        return opts;
    });
}

var vm = new ViewModel(json);
ko.applyBindings(vm);

Here's a working jsFiddle: http://jsfiddle.net/psteele/7vcqX/

If this is something you're going to do a lot (bind a select list to the properties of an object) you may want to consider creating a custom binding handler.


--
You received this message because you are subscribed to the Google Groups "KnockoutJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email to knockoutjs+...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Reply all
Reply to author
Forward
0 new messages