简体   繁体   中英

Knockout.js - select value not set

I am using knockout.js, and it's not setting the value of an empty option (Four):

<select data-bind="value: item.widgetValue, attr: {id: item.widgetName, name: item.widgetName}, options: item.options, optionsText: ‘label’, optionsValue: ‘value’” id=”fld-“ name=”fld0”>
  <option value=”one”>One</option>
  <option value=”two”>Two</option>
  <option value=”three”>Three</option>
  <option value>Four</option>
  ...
</select>

This is creating a problem: when you're on any option and try to select Four, it selects One; it will only select Four the second time you try to select it.

I have tried changing the knockout data-bind to fix it:

value: $.trim(item.widgetValue)

This allows you to select Four immediately, but incorrectly shows One as being selected after you submit the form with Four selected.

Any ideas as to what could be causing this, or how to fix it?

You shouldn't be manually setting options if you are using the options binding on your select element. If those are being dynamically created by the binding (ie. you are actually using item.options for your source) then check the objects you are binding the select element to -

item.options probably looks like this (missing a value or is somehow not like the other options) -

item.options = [
    { label: 'someLabel1', value: 'someValue1' },
    { label: 'someLabel2', value: 'someValue2' },
    { label: 'someLabel3', 'someValue3' }
    ];

but should be a more uniform object like this (well defined model) -

function optionModel(label, value) {
    var self = this;
    self.label = ko.observable(label);
    self.value = ko.observable(value);
}

item.options = [
    new optionModel('someLabel1', 'someValue1'),
    new optionModel('someLabel2', 'someValue2'),
    new optionModel('someLabel3', 'someValue3')
    ];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM