Knockout - readonly model binding from selected item in dropdown
http://stackoverflow.com/questions/9769955/knockout-readonly-model-binding-from-selected-item-in-dropdown
HTML
<script src="https://github.com/downloads/SteveSanderson/knockout/knockout-2.0.0.debug.js"></script>
<script src="https://raw.github.com/SteveSanderson/knockout.mapping/master/knockout.mapping.js"></script>
<table id="some-table">
<thead>
<tr>
<th>
[Actions]
</th>
<th>
Code
</th>
<th>
Location
</th>
<th>
Name of Water
</th>
<th>
WFD Code
</th>
</tr>
</thead>
<tbody data-bind="foreach: items">
<tr>
<td>
ACTIONS - UP/DOWN/DELETE
</td>
<td>
<!-- this should bind codes to current item items[x] -->
<select data-bind="options: $parent.codes, optionsText: 'name', value: code, optionsCaption: 'Select Code...'"></select>
</td>
<td>
<!-- location should be from items[x] not from codes -->
<label data-bind="visible: code, text: location" />
</td>
<td>
<label>E</label><label data-bind="visible: code, text: easting" />
<label>N</label><label data-bind="visible: code, text: northing" />
</td>
<td>
<label data-bind="visible: code, text: waterName" />
</td>
<td>
<label data-bind="visible: code, text: wfdCode" />
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="6">
<button class="btn" data-bind="click: addRow">Add</button>
</td>
</tr>
</tfoot>
</table>
<button class="btn" data-bind="click: save">Save</button>
JavaScript
function Item() {
this.code = ko.observable();
this.location = ko.observable();
this.easting = ko.observable();
this.northing = ko.observable();
this.waterName = ko.observable();
this.wfdCode = ko.observable();
}
var jsonModel = {
items: [ {
code: 'ID_01',
location: 'some_place',
easting: '435',
northing: '345',
waterName: 'some_name',
wfdCode: 'some_code'
}, {
code: 'ID_02',
location: 'some_place2',
easting: '4352',
northing: '3452',
waterName: 'some_name2',
wfdCode: 'some_code2'
}]
};
var viewModel = ko.mapping.fromJS(jsonModel);
viewModel.codes = ko.observableArray([ {
name: 'myName',
code: 'ID_01',
location: 'some_place',
easting: '435',
northing: '345',
waterName: 'some_name',
wfdCode: 'some_code'
}, {
name: 'myName2',
code: 'ID_02',
location: 'some_place2',
easting: '4352',
northing: '3452',
waterName: 'some_name2',
wfdCode: 'some_code2'
}, {
name: 'myName3',
code: 'ID_03',
location: 'some_place3',
easting: '4352',
northing: '3452',
waterName: 'some_name3',
wfdCode: 'some_code3'
}, {
name: 'myName4',
code: 'ID_04',
location: 'some_place4',
easting: '4352',
northing: '3452',
waterName: 'some_name4',
wfdCode: 'some_code4'
}]);
viewModel.addRow = function(data) {
viewModel.items.push(new Item());
};
viewModel.save = function() {
var json = ko.mapping.toJS(viewModel);
alert('This should execute and pass model to action\nAction model is defined and looks like jsonModel\nso all items from table should be mapped to items\nExecute POST JSON: ' + JSON.stringify(json));
};
ko.applyBindings(viewModel);