Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cascading Dropdown using knockout.js [closed]

I am trying to build a three step drop down series. Easiest example I could think of was building a year/make/model drop down set.

I have tried following the example at and using another fiddle at (another fiddle url ending with jsfiddle.net/rniemeyer/V2gvT/ ), but am having problems with the databinding.

My fiddle has a static list of year/make/model objects to use, and the year list binds properly, but never get the make/model lists to databind.

My Fiddle

Simple Markup

<label for="ddlYear">Year</label>
<select id="ddlYear" data-bind="options: years, value: selectedYear"></select>

<label for="ddlMake">Make</label>
<select id="ddlMake" data-bind="options: makes, value: selectedMake'"></select>

<label for="ddlModel">Model</label>
<select id="ddlModel" data-bind="options: models"></select>

Script

var viewModel = {
    selectedYear: ko.observable(""),
    selectedMake: ko.observable(""),
    selectedModel: ko.observable("")    
};

viewModel.years = ko.dependentObservable(function() {
    return Enumerable.From(makeModelList).Select(function(it) {
      return it.year;
    }).OrderBy(function(it) {
      return it.year;  
    }).Distinct().ToArray();
}, viewModel);

viewModel.makes = ko.dependentObservable(function() {
    var selectedYear = this.selectedYear();
    return Enumerable.From(makeModelList).Where(function(it) {
        return it.year == selectedYear;
    }).Select(function(it) {
      return it.make;  
    }).ToArray();
}, viewModel);

viewModel.models = ko.dependentObservable(function() {
    var selectedYear = this.selectedYear();
    var selectedMake = this.selectedMake();
    return Enumerable.From(makeModelList).Where(function(it) {
        return it.year == selectedYear;
    }).Where(function(it) {
      return it.make == selectedMake;  
    }).Select(function(it) {
      return it.model;  
    }).ToArray();
}, viewModel);

ko.applyBindings(viewModel);

Data is defined in the script block window

var makeModelList = [
{
    year: 1984,
    make: 'Chevrolet',
    model: 'Camaro'},

etc.

Tried to make it as simple as I could, but can't quite figure out why the selects are databinding like the examples I've tried to mimic.

like image 206
Robin Giltner Avatar asked May 22 '12 18:05

Robin Giltner


1 Answers

You have unnecessary ' in this line (after word selectedMake):

<select id="ddlMake" data-bind="options: makes, value: selectedMake'"></select>

just remove it.

fixed fiddle - http://jsfiddle.net/Yrkbd/8/

like image 68
Artem Avatar answered Nov 13 '22 04:11

Artem