Reputation: 235
I need to bind the html 'select' (dropdown) below. When I tried to bind the below code outside the <tbody data-bind="foreach: obtainedMarksArr">
code then It works well. But you can see in HTML code below that when we placed it inside the <tbody data-bind="foreach: obtainedMarksArr">
code then it gives following error:
Error: "0x800a1391 - JavaScript runtime error: 'obtainedMarksArr' is undefined".
------------------------ Page-Code -----------------------------
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.7.1.js"></script>
<script src="Scripts/knockout-2.3.0.js"></script>
<link href="Content/myTestStyleSheet1.css" rel="stylesheet" />
<script type="text/javascript">
var uri = 'api/students';
function AppViewModel(item) {
var self = this;
self.obtainedMarksArr = ko.observableArray();
for (var i = 0; i < item.ObtainedMarksList.length; i++) {
self.obtainedMarksArr.push({ course: item.ObtainedMarksList[i].courseName, totalmarks: item.ObtainedMarksList[i].TotalMarks, obtainedMarks: item.ObtainedMarksList[i].ObtainedMarks });
}
}
//---------------------------------------------------------------------------------------------
$(document).ready(function () {
$.getJSON(uri)
.done(function (data) {
//Apply binding here:
ko.applyBindings(new AppViewModel(data));
});
});
</script>
</head>
<body>
<div id="div1">
<table class="marginTable2">
<thead>
<tr class="ThColor">
<th class="textCenter ThColor topThColor" colspan="4">Obained Marks List</th>
</tr>
<tr class="ThColor">
<th class="textLeft ThColor">Course</th>
<th class="textLeft ThColor">Total Marks</th>
<th class="textLeft ThColor">Obtained Marks</th>
</tr>
</thead>
<tbody data-bind="foreach: obtainedMarksArr">
<tr class="TrColor">
<td class="textLeft"><select data-bind="options: obtainedMarksArr, optionsText: 'course'"></select></td>
<td class="textLeft"><input data-bind="value: totalmarks" /></td>
<td class="textLeft"><input data-bind="value: obtainedMarks" /></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Am I missing something. I really appreciate your answer.
Thanks.
Upvotes: 1
Views: 181
Reputation: 4101
Inside the foreach: obtainedMarskArr
you context is changed to just that.
The <select data-bind="options: obtainedMarksArr
is the problem here, should be <select data-bind="options: obtainedMarks
because you are working with these objects now, for each tr
you create
{
course: item.ObtainedMarksList[i].courseName,
totalmarks: item.ObtainedMarksList[i].TotalMarks,
obtainedMarks: item.ObtainedMarksList[i].ObtainedMarks
}
Or, if you need the dropdown to be obtainedMarskArr, you could do: <select data-bind="options: $root.obtainedMarksArr
Upvotes: 3