2

I have a function that puts an object into an observable called "detailedStudent" which will display some of the student's fields in a modal. Here's the problem:

  1. I start with a field that has a value of false. (IncludeInStudentSiteResults)
  2. I set the 'student' object inside 'detailedStudent' which displays the dropdown list (simulating a modal popup).
  3. The field's value gets set to true, which is the first option in the dropdown list.

Here's a jsFiddle that reproduces the problem: http://jsfiddle.net/62fDB/16/

Vladimir Posvistelik
  • 3,843
  • 24
  • 28
Adam Levitt
  • 10,316
  • 26
  • 84
  • 145

3 Answers3

1

Dropdown option values are strings (not booleans). Update your data initialization like so

...
"IncludeInStudentSiteResults": "false",
...

JSfiddle:http://jsfiddle.net/62fDB/22/

or use a solution from the following post Knockoutjs (version 2.1.0): bind boolean value to select box

Community
  • 1
  • 1
Aleksey Cherenkov
  • 1,405
  • 21
  • 25
  • This is certainly helpful and a step in the right direction, but the boolean value is getting automatically serialized into JSON as a boolean. Is there a preferred way of having booleans as dropdown option values? – Adam Levitt Jun 05 '12 at 15:13
  • 1
    This might help [Knockoutjs (version 2.1.0): bind boolean value to select box](http://stackoverflow.com/questions/10510683/knockoutjs-version-2-1-0-bind-boolean-value-to-select-box) – Aleksey Cherenkov Jun 05 '12 at 15:18
0

This is your version:

function StudentViewModel() {
    var self = this;
    this.students = ko.observableArray([]);
    this.detailedStudent = ko.observable();

    this.clickMe = function(student) {
        alert(student.IncludeInStudentSiteResults());
        self.detailedStudent(student);
        alert(student.IncludeInStudentSiteResults());
    }
}​

Try to use my version:

function StudentViewModel() {
    var self = this;
    this.students = ko.observableArray([]);
    this.detailedStudent = ko.observable();

    this.clickMe = function(student) {
        alert(student.IncludeInStudentSiteResults());
        self.detailedStudent(ko.observable(student));
        alert(student.IncludeInStudentSiteResults());
    }
}​

JSfiddle: http://jsfiddle.net/62fDB/23/

Vladimir Posvistelik
  • 3,843
  • 24
  • 28
  • The issue with your version is that the detailedStudent never gets bound and thus the dropdown never appears on the page. – Adam Levitt Jun 05 '12 at 14:53
  • Using your updated fix, I get a pretty common console JavaScript error: Unable to parse bindings. Message: ReferenceError: IncludeInStudentSiteResults is not defined; Bindings value: value: IncludeInStudentSiteResults – Adam Levitt Jun 05 '12 at 15:15
0

Here's a fiddle that contains the answer to my question. I don't love that I had to write a custom binding, but the alternative would be to use an enum instead of data-binding to a boolean.

http://jsfiddle.net/ekyDh/2/

Adam Levitt
  • 10,316
  • 26
  • 84
  • 145