user2598808
user2598808

Reputation: 643

knockout.js html option - show default value when observable is null

Below is my code to bind a dropdown in ko.js

HTML:

 <select data-bind="options: myList, value: _selectedPart , optionsCaption: 'None'"></select>

myList is being populated from Database and is successfully displayed with all the values.

I am able to successfully save a value as well.

Issue

When I dont select any value, the default value is None. So, when there is no value(null) for this field in DB - I want to display the default option value as "None", which is not happening.

var _selectedPart = ko.observable();
var itemSelected = // get value from DB;

if (itemSelected) {
    _selectedPart(parnerSelected);// works fine // 
} else {
    // select Default option value as "None"
}

I tried to check null in HTML. Below code, doesnt work:

 <select data-bind="options: myList, value: selectedPart == null ? 'None' : selectedPart "></select>

Upvotes: 1

Views: 1638

Answers (2)

Jonathan
Jonathan

Reputation: 245

You need to add valueAllowUnset to your data-bind because null is not in the bound array:

<select data-bind="options: myList,
                   value: _selectedPart,
                   optionsCaption: 'None',
                   valueAllowUnset: true"></select>

See here:

http://knockoutjs.com/documentation/value-binding.html#using-valueallowunset-with-select-elements

Upvotes: 0

Tomalak
Tomalak

Reputation: 338228

Set the observable's value to undefined to trigger the default optionsCaption.

function Sample() {
    var self = this;
  
    this.myList = ['A', 'B', 'C'];
    this._selectedPart = ko.observable();
  
    this.selectFromDB = function () {
        // random item to simulate "get from DB"
        var randomIndex = Math.floor(Math.random() * this.myList.length);
        var value = self.myList[randomIndex];
        self._selectedPart(value);
    };
    this.reset = function () {
        self._selectedPart(undefined);
    };
}

ko.applyBindings(new Sample());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<button data-bind="click: selectFromDB">Select Item</button>
<button data-bind="click: reset">Reset</button>
<br>
<select data-bind="options: myList, value: _selectedPart, optionsCaption: 'None'"></select>

You can simplify your code by getting rid of the if/else like this:

var itemSelected = // get value from DB;
_selectedPart(itemSelected || undefined);

Upvotes: 1

Related Questions