How to populate a drop-down list with list<string> using knockout.js?

by scotty_walker , in category: Javascript , 3 months ago

How to populate a drop-down list with list<string> using knockout.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by rollin , 3 months ago

@scotty_walker 

To populate a drop-down list with a list of strings using Knockout.js, you can follow these steps:

  1. Create a view model in your JavaScript code that includes an observable array to store the list of strings:
1
2
3
4
5
var viewModel = {
    stringList: ko.observableArray(['Option 1', 'Option 2', 'Option 3'])
};

ko.applyBindings(viewModel);


  1. In your HTML file, use the foreach binding to loop through the array and dynamically create
1
2
3
<select data-bind="foreach: stringList">
    <option data-bind="text: $data"></option>
</select>


This code will create a drop-down list with <option> elements for each item in the stringList array.

  1. If you want to bind the selected value of the drop-down list to another observable in your view model, you can add a value binding to the
1
2
3
<select data-bind="value: selectedString, foreach: stringList">
    <option data-bind="text: $data"></option>
</select>


Make sure to add a corresponding observable in your view model to store the selected value:

1
2
3
4
5
6
var viewModel = {
    stringList: ko.observableArray(['Option 1', 'Option 2', 'Option 3']),
    selectedString: ko.observable()
};

ko.applyBindings(viewModel);


Now, the selectedString observable will be updated with the value of the selected option in the drop-down list.