Remove an option in dropdown list knockout js

881 Views Asked by At

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.

1

There are 1 best solutions below

1
DaveB On BEST ANSWER

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>