Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

knockout.js

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/

like image 475
David MacCrimmon Avatar asked Aug 21 '13 11:08

David MacCrimmon


2 Answers

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.

like image 101
Rico Suter Avatar answered Nov 17 '22 17:11

Rico Suter


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('');
like image 12
Tim B James Avatar answered Nov 17 '22 15:11

Tim B James