Raj123
Raj123

Reputation: 981

How to clear the selected values in Select2

I am working on a web application where I have a select element. I am binding it to a collection. I am doing this using knockout.

Here is my code:

    <select multiple class="form-control input-sm"
                                    data-bind="options: ConfigurationParameters ,optionsValue: 'Bit63', optionsText: 'DisplayText', selectedOptions: SelectedConfigParams,select2: { placeholder: 'Choose...' }"></select>

Here is my binding handler:

    ko.bindingHandlers.select2 = {
init: function (element, valueAccessor) {
    var options = ko.toJS(valueAccessor()) || {};
    setTimeout(function () {
        $(element).select2(options);
    }, 0);
  },
    update: function (element, valueAccessor, allBindings) {
    console.log("update called");
}
};

I have other select elements all with similar functionality. When a user selects required information and click submit, I am saving the data to a data base. After doing this I need to clear the values in the select boxes. I wrote a code to remove all the elements from 'SelectedConfigParams'. But the values are not getting removed from the select element. In the image, you can see, after clearing the selected options , the select element is still showing the previous selected values. (SelectedConfigParams is an ko.observableArray()).

In the image you can see after clearing the selected options the select element is still showing the previously selected elements.

Upvotes: 2

Views: 1648

Answers (1)

JotaBe
JotaBe

Reputation: 39055

Whe you create a custom binding you need to specify two different functions:

  • init: this is called once, when the binding is done. You should use it to add event handlers, and set default attributes for the element, apply jQuery plugins...
  • update: this is called after init, and whenever any used observable or computed observable changes. The observables can be accessed through the valueAccessor, which allows you to get the value or observable specified after the bindingName:, or through any of the other parameters (allBindings, viewModel, bindingContext). You should update the state of the element, the applied plugins and so on in this function, depending on the new observable values

So, what you need to do is:

  1. Create the init function to initialize the select2
  2. Create the update function to change the state of the select2 plugin
  3. Create an observable in your viewmodel and bind it to your element using your custom binding (this will call init, and update, with the initial value of the observable)
  4. Modify the observable in your viewmodel. When you do so, the update function of your binder will be called, so that the state of your element or plugin can be updated

Please see Knockout's custom binding docs for more info.

Upvotes: 4

Related Questions