David MacCrimmon
David MacCrimmon

Reputation: 966

Knockout.js reset the value of a select back to its default value

I have a select box that I'm populating using knockout. Once the user has made some selections on the form I'd like to reset that select box back to its default value that's set in the optionsCaption. How would you go about doing this? I've tried to set it to an empty string however this leaves it with the value that the user has selected.

Here is my code:

<select data-bind="options: components, optionsValue: 'Component', optionsText: 'Component', optionsCaption: 'Choose Component', value: component"></select>

Here is the js:

self.components = ko.observableArray(["Component":"1234", "Component":"5678"]);
self.component = ko.observable();

What I then try to do in another section is:

self.component("");

However this appears to have no effect.

EDIT : Here is a fiddle http://jsfiddle.net/BASY4/

Upvotes: 12

Views: 20553

Answers (2)

Rico Suter
Rico Suter

Reputation: 11858

Use

self.component(null);

instead of

self.component("");

Working jsfiddle.

Other values are only allowed if they are in the source list (here self.components) otherwise the value binding is resetted immediately.

Upvotes: 26

Tim B James
Tim B James

Reputation: 20364

Depending on what version of knockoutjs you use, will change the answer to this question.

If you are using version 2.2.1 like the jsfiddle is using, then you will need to use;

self.component(null);
// or
self.component(undefined);

If you were to change this version to the latest version 2.3.0 then you can actually use;

self.component(null);
// or
self.component(undefined);
// OR
self.component('');

Upvotes: 12

Related Questions