Search code examples
knockout.jsknockout-2.0knockout-mvc

Remove an option in dropdown list knockout js


Hello Is there any way I can remove an option from a knockout dropdown list at initial loading.

<select data-bind="options: Reasons,  optionsText: 'Title', optionsValue: 'Id', value: SelectReason,
optionsCaption: 'Choose..', optionsAfterRender: setOptionRemove"></select>

The code in the viewmodel, I'm trying to do it using optionsAfterRender,

        self.setOptionRemove= function(option, item) {
            if(item.Id == 1){
            ko.applyBindingsToNode(option, { remove: item.remove}, item);
             }
         }

I want to use the first option as a radio button.

Thanks.


Solution

  • Maybe instead you could bind the list to a computed that would exclude the option you don't want in the list instead of trying to remove it.

    self.filteredReasons = ko.computed(function() {
         return ko.utils.arrayFilter(self.Reasons(), function(reason) {
              if(reason.Id !== 1) {
                   return true;
              }
         });
    });
    

    Updated binding:

    <select data-bind="options: filteredReasons ,  optionsText: 'Title', optionsValue: 'Id', value: SelectReason, optionsCaption: 'Choose..'"></select>