Working with Selects (dropdowns) in knockout.js

If you’re like me, I am always excited to try new tools and technologies so in this article I am going to show you how to use knockout.js to bind a dropdown list. It is very similar to non-knockout.js but there is a little bit of a difference. Let’s get started. One quick note is that there are a couple of different ways to do this. If the select name is the same as the value then there is a little easier way to do this, however; in this example I want the name and the value to be different.

Start with creating a jQuery Ajax call. This is pretty much the same as you would for any AJAX method.

$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "../api/Dropdown",
data: "{}",
dataType: "json",
async: false,
success: function (data) {
$.each(data, function (index, value) {
array.push(value);
});
}
});

The result coming back from your server call would look something like this.

[{"CountryId":4,"CountryName":"United States"},{"CountryId":5,"CountryName":"Germany"},{"CountryId":6,"CountryName":"Spain"},{"CountryId":7,"CountryName":"England"},{"CountryId":8,"CountryName":"China"},{"CountryId":9,"CountryName":"South America"},{"CountryId":10,"CountryName":"Canada"},{"CountryId":11,"CountryName":"Japan"}]

Then in your knockout.js binding function you would populate the observable with the array (created above)

self.CountryList = ko.observableArray(array);

//Sets The Text to be the value of the Select
self.regionNametext = ko.computed(function() {
         var CountryNametext
         ko.utils.arrayForEach(array, function (item) {
         if (self.CountryId() == item.CountryId) {
         CountryNametext = item.CountryName;
       };
    });
    return CountryNametext;
},self)

In your html you would use the following to bind the text to what a user sees and the value that will be stored in the value field of the select;

  CountryId:
 <select id="ddlCountryName" data-bind="options: CountryList, optionsText: "CountryName", optionsValue: "CountryId", optionsCaption: "Choose...",value: $root.CountryId"></select>

Now when you change the dropdown the value of the dropdown is now populated in the regionNametext..

You can now use it anyway you want.

Looking for quality web hosting? Look no further than Arvixe Web Hosting!

Tags: , , , , | Posted under Programming/Coding | RSS 2.0

Author Spotlight

David Bauernschmidt

David Bauernschmidt

I live in the historical triangle of Virginia where I am married with two daughters. I have spent over 13 years working for a Fortune 500 company in the computer area. I started in VB 6.0 and by the time I ended my employment I was supervising a development team where we built many web applications. When my first daughter was born I wanted to spend more time with her so I left and became a programmer analyst for local government as well as launch my own company. Since then I have grown James River Webs into a profitable web design and application company helping small businesses create a big presence on the internet. As an employee I have created web application used by citizens and other companies. I enjoy fly fishing, and spending time with my family. I also enjoy learning new approaches and development tools when it comes to developing applications.

2 Comments on Working with Selects (dropdowns) in knockout.js

  1. Siraj says:

    Hi David,

    Nice one, short and clear.

    I ran into small issue with Knockout JS. I have a Form bound to a strongly type model. I have implemented create (submit), update, remove all the functions and all works.

    Initially Create form was implemented using @Html.EditorForModel(), as I needed to use a dropdown for ‘countryid’ field now I am using HTML helpers for each field instead.

    @Html.TextBoxFor(model => model.Name, new { data_bind = “model:Name” })

    when I submit I noted that CountryId is not binding back to the model and backend database (which is using dropdown list selection).

    What is the current way to store the selected value back to model.

    Any help.

    Best Regards
    Siraj

  2. Can you send me part of the code you are having problem in. You can send it to my david@jamesriverwebs.com account?

Leave a Reply

Your email address will not be published. Required fields are marked *


7 − = 6

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>