Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get Knockout to do a simple 'options' binding

I've got the following simple setup in knockout

var data = { 
  'Divisions': [
    { 'divID' : '105' },
    { 'divID' : '103' }
  ]
};

var viewModel = ko.mapping.fromJS(data);

ko.applyBindings(viewModel);

and the following HTML that does not properly bind

<select data-bind="
  options: Divisions, 
  optionsText: divID,
  optionsCaption: 'Choose...'">
</select>

onload I get 'ReferenceError: divID is not defined'.

If I use the following binding, it works

<select data-bind="
  options: Divisions, 
  optionsText: function(item) { 
    return item.divID(); 
  }, 
  optionsCaption: 'Choose...'">
</select>

For reference:

Working binding in jsbin, with the ugly binding

Non working version in jsbin that looks like it should work, with the clean binding

I suspect that this is all being caused by ko.mapping.fromJS making every child in Divisions an observable, thus making it so that I can't simply access everything as a simple property name, but I just found a similar example that is doing the exact same thing!

like image 461
Allen Rice Avatar asked Feb 13 '26 09:02

Allen Rice


1 Answers

You forgot the single quotes around your optionsText

<select data-bind="
  options: Divisions, 
  optionsText: 'divID',
  optionsCaption: 'Choose...'">
</select>
like image 155
Allen Rice Avatar answered Feb 15 '26 00:02

Allen Rice



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!