1

Im rewriting some standard jquery dynamic select menus into knockout. In pain jquery it adds options to a select menu with this:

 $.each(data.DropDownOptions, function() {
     if (this.ID != undefined) {
          $(".SelectDDL").append($("<option value='" + this.ID + "'></option>").html(this.Option));
           }
      });

the options frequently have " symbols in it which at the point "this.Option" appears as &quot because its JSON. But in the actual dropdown they appear as " (the actual symbol).

I rewrote it into knockout using practically the same logic and using a template like this.

function CarOptionMenu(data) {
    return {
        CarOptions: ko.observableArray(data),
        selection: ko.observable()
    }
}
function KnockoutModel() {
    var self = this;
    self.menuWrapper = ko.observableArray([]);
}

var list = new KnockoutModel();
ko.applyBindings(list );

and in place of the above jQuery function it adds options like this:

  list.menuWrapper.push(new CarOptionMenu(data.DropDownOptions));

Which works fine except the &quot remains &quot and never gets parsed into the " symbol. Any idea on how to fix that?

--EDIT-- Here is the select element and template:

    <script type="text/html" id="car-option-menu-template">
        <select data-bind='options:CarOptions, optionsText:"Option",optionsValue:"ID",value: selection' style="width: 100% !important; margin-top: 5px;"></select>
    </script>
    <div data-bind="template: { name: 'car-option-menu-template', foreach: menuWrapper}"></div>
DasBeasto
  • 2,082
  • 5
  • 25
  • 65
  • How does your `data-bind` look like in your ` – haim770 Mar 23 '15 at 16:33
  • @haim770 added it to the bottom of my post – DasBeasto Mar 23 '15 at 16:58
  • My bet is that `optionsText` executes a function using `textContent` or similar instead of `innerHTML`. You still haven't revealed the most important piece of the puzzle: what is the function which builds a single option (eg all items in `data.dropDownOptions`)? On the other hand, what prevents you from converting the JSON to plain JS before passing it? It's kind of weird to have options containing JSON strings no? – webketje Mar 23 '15 at 19:16

1 Answers1

1

There are a few built in functions to encode and decode json strings such as ko.toJSON and ko.utils.parseJson, but it sounds like you have some html entity encoding mixed in with your json.

You can add a function to decode the html encoded bits when you push the data into the CarOptionMenu. Refer to this question on html encoding: HTML Entity Decode

I would recommend taking a look at why you have html entity encoding in your json in the first place though. Quotes are escaped with a slash (\") in json strings not with &quot.

Community
  • 1
  • 1
Jason Spake
  • 4,293
  • 2
  • 14
  • 22