0

I am new to Knockout.js can anyone let me know how can we populate b dropdowns using Knockout.js. I have two dropdowns : Employee and Course.

<select id="Employee">
                    <option value="1" selected="selected">1</option>
                    <option value="2">2</option>

                </select>

<select id="Course">
                    <option value="Course1" selected="selected">Course1</option>
                    <option value="Course12">Course12</option>

                </select>

so my requirement is if i select Employee "1" then i should be able to see only Course1. if i select Employee "2" i should be able to see both Course1 and Course2.

1 Answer 1

3

Without more information about your view model, it is pretty hard to answer, but this could be your javascript:

(function (myViewModel, $, undefined) {
    myViewModel.selectedEmployee = ko.observable(1);
    myViewModel.courses = ko.dependentObservable(function () {
        var result = ["Course1"];
        if (myViewModel.selectedEmployee() === '2') {
            result.push("Course2");
        }
        return result;
    });        
}(window.myViewModel = window.myViewModel || {}, jQuery));
ko.applyBindings(myViewModel);

and then your HTML:

<select id="Employee" data-bind="value: selectedEmployee">
    <option value="1" selected="selected">1</option>
    <option value="2">2</option>
</select>

<select id="Course" data-bind="options: courses"></select>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.